吾知网

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 6108|回复: 0

Python 汉字简体和繁体的相互转换

[复制链接]
发表于 2019-1-19 14:13:05 | 显示全部楼层 |阅读模式

其实利用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把中文字符串進行繁體和簡體中文的轉換
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|吾知网 ( 粤ICP备13013563号-1 )

GMT+8, 2024-3-28 23:51 , Processed in 1.062500 second(s), 8 queries , Memcache On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表