Python 繁体中文与简体中文相互转换

工作中需要将繁体中文转换成简体中文
上网找了些资料,发现这个包最方便

安装方法

不需要什么安装方法,只需要把这两个文件下载下来,保存到与代码同一目录下即可

https://raw.githubusercontent.com/skydark/nstools/master/zhtools/langconv.py
https://raw.githubusercontent.com/skydark/nstools/master/zhtools/zh_wiki.py

繁体转简体

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)

    '''
    输出结果:
        忧郁的台湾乌龟
    '''

简体转繁体

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)

    '''
    输出结果:
        憂郁的臺灣烏龜
    '''

完整代码

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,NLP,python,NLP)