python获取同音字
作者:互联网
利用汉字转拼音项目,简单实现获取一个汉字的同音字
1. 安装汉字转拼音包
pip install pypinyin
2. 获取所有汉字的拼音表示,相同拼音的汉字存储在以拼音为key的字典中,考虑声调
from pypinyin import pinyin, lazy_pinyin, Style
import os
import pickle
def get_all_char_pinyin():
path = "all_3500_chars.txt"
pinyin_dict = {}
with open(path, "r", encoding="utf-8") as f:
for line in f.readlines():
ch = line.strip()
ch_pinyin = pinyin(ch, style=Style.TONE3, heteronym=False)
# heteronym 是否启用多音字模式
for p_li in ch_pinyin:
for p in p_li:
if p not in pinyin_dict:
pinyin_dict[p] = [ch]
else:
pinyin_dict[p].append(ch)
return pinyin_dict
all_3500_chars.txt 是常见的3500汉字,一行一个汉字,例如:
的
年
是
一
为
在
中
国
于
人
有
大
和
个
了
3. 获取同音字
if __name__ == '__main__':
pinyin_dict = get_all_char_pinyin()
# 获取同音汉字
similarity_dict = {}
match_char = "明"
ch_pinyin = pinyin(match_char, style=Style.TONE3, heteronym=False)
res = []
for p_li in ch_pinyin:
for p in p_li:
print(p)
if match_char in pinyin_dict[p]:
pinyin_dict[p].remove(match_char)
res.extend(pinyin_dict[p])
print(res)
4. 输出
ming2
['名', '铭', '鸣', '冥']
相关链接
文本纠错之获取形近字http://https://blog.csdn.net/jclian91/article/details/118345177?spm=1001.2014.3001.5502
标签:ch,拼音,获取,python,pinyin,汉字,char,同音字,dict 来源: https://blog.csdn.net/ltochange/article/details/122811731