Python实现简繁体转换,现在的人玩得老花了

1、opencc-python

首先介绍opencc中的Python实现库,它具有安装简单,翻译准确,使用方便等优点。对于我们日常的需求完全能够胜任。

; 1.1安装opencc-python

首先在terminal中安装opencc-python。

pip install opencc-python

1.2内建的opencc翻译配置

这里有四种内建的opencc翻译配置:

•t2s - 繁体转简体(Traditional Chinese to Simplified Chinese)

•s2t - 简体转繁体(Simplified Chinese to Traditional Chinese)

•mix2t - 混合转繁体(Mixed to Traditional Chinese)

•mix2s - 混合转简体(Mixed to Simplified Chinese)

1.3简繁体转换

import opencc  Python插件/素材/.源码Q群:903971231####
cc = opencc.OpenCC('t2s')
print(cc.convert(u'Open Chinese Convert(OpenCC)開放中文轉換,是一個致力於中文簡繁轉換的項目,提供高質量詞庫和函數庫(libopencc)。'))

输出结果如下:

Python实现简繁体转换,现在的人玩得老花了

2、zhtools

2.1安装

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

2.2简繁体转换

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))

转换后的结果为:

这种方法的优点是重量轻、使用方便、简明扼要,但翻译可能不准确。

[En]

The advantages of this method are lightweight, easy to use and concise, but the translation may not be accurate.

3、zhconv

3.1zhconv安装

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

pip install zhconv

3.2使用方法

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

zh-cn 大陆简体

zh-sg 马新简体(马来西亚和新加坡使用的简体汉字)

zh-tw 台灣正體(台湾正体)

zh-hk 香港繁體(香港繁体)

zh-hans 简体

zh-hant 繁體(繁体)
方法1:直接导入zhconv1

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

from zhconv import convert

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

转换结果为:

Python实现简繁体转换,现在的人玩得老花了

4、文档的简繁体转换

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

pip install python-docx

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

Python源码/素材/解答Q群:903971231###
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')

转换前:

转换后:

如此一来,我们就实现了从《匆匆》文档到传统版本的转换。

[En]

In this way, we have implemented the conversion of the “hurried” document into a traditional version.

到此这篇关于Python实现简繁体转换的文章就介绍到这了,更多相关Python 简繁体转换以及其他内容请继续关注之后的相关文章!

最后

我们为大家揭秘雪球网(https://xueqiu.com/) 最新所展示的沪深证券和港股关注人数增长Top10。

Python实现简繁体转换,现在的人玩得老花了

Original: https://www.cnblogs.com/1234567FENG/p/16400639.html
Author: 蚂蚁爱Python
Title: Python实现简繁体转换,现在的人玩得老花了

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/499273/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球