本文实例讲述了Python实现繁体中文与简体中文相互转换的方法。分享给大家供大家参考,具体如下:
工作中需要将繁体中文转换成简体中文
上网找了些资料,发现这个包最方便:https://github.com/skydark/nstools/tree/master/zhtools
安装方法
不需要什么安装方法,只需要把这两个文件下载下来,保存到与代码同一目录下即可
https://raw.githubusercontent.com/skydark/nstools/master/zhtools/langconv.py
https://raw.githubusercontent.com/skydark/nstools/master/zhtools/zh_wiki.py
繁体转简体:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
from langconv import * def Traditional2Simplified(sentence): ''' 将sentence中的繁体字转为简体字 :param sentence: 待转换的句子 :return: 将句子中繁体字转换为简体字之后的句子 ''' sentence = Converter( 'zh-hans' ).convert(sentence) return sentence if __name__ = = "__main__" : traditional_sentence = '憂郁的臺灣烏龜' simplified_sentence = Traditional2Simplified(traditional_sentence) print (simplified_sentence) ''' 输出结果: 忧郁的台湾乌龟 ''' |
简体转繁体:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
from langconv import * def Simplified2Traditional(sentence): ''' 将sentence中的简体字转为繁体字 :param sentence: 待转换的句子 :return: 将句子中简体字转换为繁体字之后的句子 ''' sentence = Converter( 'zh-hant' ).convert(sentence) return sentence if __name__ = = "__main__" : simplified_sentence = '忧郁的台湾乌龟' traditional_sentence = Simplified2Traditional(simplified_sentence) print (traditional_sentence) ''' 输出结果: 憂郁的臺灣烏龜 ''' |
完整代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
from langconv import * def Traditional2Simplified(sentence): ''' 将sentence中的繁体字转为简体字 :param sentence: 待转换的句子 :return: 将句子中繁体字转换为简体字之后的句子 ''' sentence = Converter( 'zh-hans' ).convert(sentence) return sentence def Simplified2Traditional(sentence): ''' 将sentence中的简体字转为繁体字 :param sentence: 待转换的句子 :return: 将句子中简体字转换为繁体字之后的句子 ''' sentence = Converter( 'zh-hant' ).convert(sentence) return sentence if __name__ = = "__main__" : traditional_sentence = '憂郁的臺灣烏龜' simplified_sentence = Traditional2Simplified(traditional_sentence) print (simplified_sentence) |
参考资料:
skydark:https://github.com/skydark/nstools/tree/master/zhtools
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/wds2006sdo/article/details/53583367