一、说明:
这个是我发现一个python好用的一个模块,名字就是pinyin:
主要功能就是基于普通话将汉字翻译成拼音。
安装命令:
pip install pinyin
二、简单使用:
解释我放在代码里面了,看看就懂了,不过多解释了。
1、汉字转拼音:
import pinyin
# 1、可以获取拼音和音调
# print(pinyin.get('你 好'))
print(pinyin.get('我爱你'))
# 2、只获取拼音词
# print(pinyin.get('你好', format="strip", delimiter=" "))
print(pinyin.get('小时候,我害怕黑夜', format="strip", delimiter=" "))
# 3、获取拼音,后面跟的是音调(1-4)
# print(pinyin.get('你好', format="numerical"))
print(pinyin.get('我爱你', format="numerical"))
# 4、获取汉字的拼音首字母
print(pinyin.get_initial('你好'))
运行结果:
2、汉字转英文(不能转换一个句子,如果是句子会先切分开再进行一个一个翻译,返回列表)
import pinyin.cedict
# 1、这个只能翻译出单个词,不能翻译一个句子或者短语,只能是字或者词
result = pinyin.cedict.translate_word('你')
print(result)
result = pinyin.cedict.translate_word('我爱你')
print(result)
result = pinyin.cedict.translate_word('中国')
print(result)
# 2、这个是相当于返回一个上面的列表,自动把词分开(不建议翻译一个句子)
print("*"*20)
result = list(pinyin.cedict.all_phrase_translations('你好'))
print(result)
result = list(pinyin.cedict.all_phrase_translations('我爱你'))
print(result)
result = list(pinyin.cedict.all_phrase_translations('我爱你中国'))
print(result)
运行结果:
['you (informal, as opposed to courteous 您[nin2])']
None
['China']
********************
[['你', ['you (informal, as opposed to courteous 您[nin2])']], ['你好', ['Hello!', 'Hi!', 'How are you?']], ['好', ['to be fond of', 'to have a tendency to', 'to be prone to']]]
[['我', ['I', 'me', 'my']], ['爱', ['to love', 'to be fond of', 'to like', 'affection', 'to be inclined (to do sth)', 'to tend to (happen)']], ['你', ['you (informal, as opposed to courteous 您[nin2])']]]
[['我', ['I', 'me', 'my']], ['爱', ['to love', 'to be fond of', 'to like', 'affection', 'to be inclined (to do sth)', 'to tend to (happen)']], ['你', ['you (informal, as opposed to courteous 您[nin2])']], ['中', ['to hit (the mark)', 'to be hit by', 'to suffer', 'to win (a prize, a lottery)']], ['中国', ['China']], ['国', ['country', 'nation', 'state', 'national', 'CL:個|个[ge4]']]]