1. opencc

项目地址: https://github.com/yichen0831/opencc-python/

1.1 安装:

1
pip install OpenCC

1.2 使用

  • 简体转繁体

    1
    2
    3
    from opencc import OpenCC
    cc = OpenCC('t2s')
    cc.convert("中文簡繁轉換開源項目,支持詞彙級別的轉換、異體字轉換和地區習慣用詞轉換(中國大陸、臺灣、香港、日本新字體)。不提供普通話與粵語的轉換。")
  • 繁体转简体

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import opencc

    # 创建一个繁体转简体的转换器
    convert = opencc.OpenCC('s2t')

    # 要转换的繁体文本
    traditional_text = "臺灣正頓成為全球最大的資訊消費國。"

    # 執行轉換
    simplified_text = convert(traditional_text)

    print(simplified_text) # 臺灣正頓成為全球最大的資訊消費國。
  • 具体参数

参数 说明
t2s 繁体到简体
s2tw 简体到台湾繁体
tw2s 台湾繁体到简体
s2hk 简体到香港繁体
hk2s 香港繁体到简体
s2twp 简体到台湾繁体,并转换为台湾常用词汇
tw2sp 台湾繁体到简体,并转换为中国大陆常用词汇
tw2t 台湾繁体到繁体
t2tw 繁体到台湾繁体
hk2t 香港繁体到繁体
t2hk 繁体到香港繁体
t2jp 繁体到日本新字体
jp2t 日本新字体到繁体

2. zhtools

2.1安装

利用Python实现汉字的简体和繁体相互转换的命令也有人开发过,并发布到github上,地址:https://github.com/skydark/nstools/tree/master/zhtools。下载该项目中的 zh_wiki.py 和 langconv.py 两个文件,放到python代码目录下就可以了。
2.2简繁体转换

1
2
3
4
5
6
7
from langconv import Converter

def convert(text, flag=0): #text为要转换的文本,flag=0代表简化繁,flag=1代表繁化简
rule = 'zh-hans' if flag else 'zh-hant'
return Converter(rule).convert(text)
text1 = '悄悄是别离的笙箫; 夏虫也为我沉默, 沉默是今晚的康桥'print(convert(text1))
text2 = '悄悄是別離的笙簫; 夏蟲也為我沉默, 沉默是今晚的康橋'print(convert(text2, 1))

3、zhconv

3.1 zhconv安装

zhconv库直接使用pip安装,安装命令为:

1
pip install zhconv

3.2 使用方法

zhconv支持以下地区词的转换:

  • zh-cn 大陆简体
  • zh-sg 马新简体(马来西亚和新加坡使用的简体汉字)
  • zh-tw 台灣正體(台湾正体)
  • zh-hk 香港繁體(香港繁体)
  • zh-hans 简体
  • zh-hant 繁體(繁体)

方法1:直接导入zhconv1

1
2
3
4
5
6
7
8
import zhconv
text = '此去经年,应是良辰好景虚设。便纵有千种风情,更与何人说?'
text1 = zhconv.convert(text, 'zh-hant')
text2 = zhconv.convert(text, 'zh-tw')
text3 = zhconv.convert(text, 'zh-hk')
print('转换为繁体:', text1)
print('转换为台湾正体:', text2)
print('转换为香港繁体:', text3)

方法2:导入zhconv的convert

1
2
3
4
5
from zhconv import convert

text = '此去经年,应是良辰好景虚设。便纵有千种风情,更与何人说?'
text1 = convert(text, 'zh-hant')
print('转换为繁体:', text1)

4、文档的简繁体转换

利用扩展库python-docx,可以将Word文档中的中文进行转换,简体转换为繁体:

1
pip install python-docx

这里我们使用zhconv库的方法来将word文档《匆匆》转换为《匆匆》繁体版:

1
2
3
4
5
6
7
8
9
10
from zhconv import convert
from docx import Document

word = Document('《匆匆》.docx')
for t in word.paragraphs:
t.text = convert(t.text, 'zh-hant')for i in word.tables:
for p in i.rows:
for h in p.cells:
h.text = convert(h.text, 'zh-hant')
word.save('《匆匆》繁体版.docx')