其实利用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把中文字符串進行繁體和簡體中文的轉換