Python 漢字簡體和繁體的相互轉換


其實利用python實現漢字的簡體和繁體相互轉早有人做過,並發布到github上了,地址:https://github.com/skydark/nstools/tree/master/zhtools

該項目還有其他很多跟漢字相關的功能,本文只介紹繁體和簡體相互轉換

具體方法很簡單,下載該項目中的 zh_wiki.py  和 langconv.py 兩個文件,放到python代碼目錄下就可以了.

我的python是3.5版本,所以在字符串的decode上和python2.x 有所不同,demo:

 1 from langconv import *
 2 import sys
 3 
 4 print(sys.version)
 5 print(sys.version_info)
 6 
 7 # 轉換繁體到簡體
 8 def cht_to_chs(line):
 9     line = Converter('zh-hans').convert(line)
10     line.encode('utf-8')
11     return line
12 
13 # 轉換簡體到繁體
14 def chs_to_cht(line):
15     line = Converter('zh-hant').convert(line)
16     line.encode('utf-8')
17     return line
18 
19 line_chs='<>123asdasd把中文字符串進行繁體和簡體中文的轉換'
20 line_cht='<>123asdasd把中文字符串進行繁體和簡體中文的轉換'
21 
22 ret_chs = "%s\n"%cht_to_chs(line_cht)
23 ret_cht = "%s\n"%chs_to_cht(line_chs)
24 
25 print("chs='%s'",ret_cht)
26 print("cht='%s'",ret_cht)
27 
28 file = open('ret.txt','w',encoding='utf-8')
29 file.write(ret_chs)
30 file.write(ret_cht)
31 file.close()

ret.txt文件內容

<>123asdasd把中文字符串進行繁體和簡體中文的轉換
<>123asdasd把中文字符串進行繁體和簡體中文的轉換

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM