图片来源极简壁纸
模糊词替换——拼音比对替换法 该方法用于模糊词替换
背景:因为语音识别出来的文本经常会错误,而使用文本模糊词直接替换所创建的模糊词过多,
故而有了这个方法,使用拼音比对进行替换。
- 比如我语音想说 范特树 但识别出来的文本可能是以下内容:
范特舒
凡拓速
安特树
犯错数
犯错诉
梵拓述
帆托树
梵拓树
坟拓宿
梵拓宿- 痛点:维护模糊词数量过多,新增模糊词困难,经常出现新的错误词
- 解决内容:我的拼音替换法就解决了这些痛点,维护成本低,只要加入拼音就好,匹配范围广
- 只有完全连贯匹配单字典里长度和拼音时才会替换,只匹配两个字不会替换
- 建议维护模糊词字典长度至少2个,且名词不是常用词,要考虑词语常问的情况
- 完整代码在下面
pingyinReplace.json文件
[
{
"范": [
"fan",
"fa",
"fang",
"fen",
"an"
],
"特": [
"tuo",
"te"
],
"树": [
"shu",
"su"
]
}
]
代码
import json
from pypinyin import pinyin, Style
# 匹配词只替换一次版本
def pingyinReplace1(text: str, replaceList: list) -> str:
"""
只有完全连贯匹配单字典里长度和拼音时才会替换
: param text: 原文本
: param replaceDict: 映射字典列表
: return : 替换后文本
"""
print(f"[原文本]:{text}")
for replaceDict in replaceList:
c_key = list(replaceDict.keys())
c_value = list(replaceDict.values())
text = [i for i in text]
num = []
for i in range(len(text)):
if len(num) == len(c_value):
break
data = pinyin(text[i], style=Style.NORMAL)[0][0]
print(f"[匹配内容] 原字:{text[i]}, 原拼音:{data}, 匹配拼音:{c_value[len(num)]}")
if data in c_value[len(num)]:
num.append(i)
else:
num.clear()
for z in range(len(num)):
text[num[z]] = c_key[z]
print(f"[替换结果]:{''.join(text)}")
return "".join(text)
# 匹配词全部替换版本
def pingyinReplace2(text: str, replaceList: list) -> str:
"""
只有完全连贯匹配单字典里长度和拼音时才会替换
: param text: 原文本
: param replaceDict: 映射字典列表
: return : 替换后文本
"""
print(f"[原文本]:{text}")
for replaceDict in replaceList:
c_key = list(replaceDict.keys())
c_value = list(replaceDict.values())
text = [i for i in text]
num = []
for i in range(len(text)):
data = pinyin(text[i], style=Style.NORMAL)[0][0]
print(f"[匹配内容] 原字:{text[i]}, 原拼音:{data}, 匹配拼音:{c_value[len(num)]}")
if data in c_value[len(num)]:
num.append(i)
else:
num.clear()
if len(num) == len(c_value):
for z in range(len(num)):
text[num[z]] = c_key[z]
num.clear()
print(f"[替换结果]:{''.join(text)}")
return "".join(text)
if __name__ == '__main__':
with open("./pingyinReplace.json", 'r', encoding="utf-8") as f:
data = json.loads(f.read())
text = "这是梵拓数吗梵拓数梵拓数"
pingyinReplace1(text, data)
pingyinReplace2(text, data)
> [原文本]:这是梵拓数穿吗
> [匹配内容] 原字:这, 原拼音:zhe, 匹配拼音:['fan', 'fa', 'fang', 'fen', 'an']
> [匹配内容] 原字:是, 原拼音:shi, 匹配拼音:['fan', 'fa', 'fang', 'fen', 'an']
> [匹配内容] 原字:梵, 原拼音:fan, 匹配拼音:['fan', 'fa', 'fang', 'fen', 'an']
> [匹配内容] 原字:拓, 原拼音:tuo, 匹配拼音:['tuo', 'te']
> [匹配内容] 原字:数, 原拼音:shu, 匹配拼音:['shu', 'su']
> [匹配内容] 原字:穿, 原拼音:chuan, 匹配拼音:['chuang', 'chuan', 'chang', 'chan', 'chong']
> [替换结果]:这是范特树吗
修复了多匹配词的一个bug
新增只替换一次和替换全部的匹配词方法

被折叠的 条评论
为什么被折叠?



