Python 使用列表替换整个单词
我有两个单词列表,分别是word_错和word_好,我需要用word_好中的正确单词替换列表中word_错的单词。我需要搜索整个单词,不区分大小写 就一个词而言,我正在使用它,它正在发挥作用:Python 使用列表替换整个单词,python,regex,Python,Regex,我有两个单词列表,分别是word_错和word_好,我需要用word_好中的正确单词替换列表中word_错的单词。我需要搜索整个单词,不区分大小写 就一个词而言,我正在使用它,它正在发挥作用: fixed = re.sub(r'\bprot\b','profit', fixed, flags=re.IGNORECASE) 我改为: def fix_fibase(texts): word_wrong= ['prot','protability','protable','protably'
fixed = re.sub(r'\bprot\b','profit', fixed, flags=re.IGNORECASE)
我改为:
def fix_fibase(texts):
word_wrong= ['prot','protability','protable','protably','prots']
word_ok = ['profit','profitability','profitable','profitably','profits']
fixed = texts
for k in range(0,5):
fixed = re.sub(r'\b' + word_wrong[k] + r'\b',word_ok[k], fixed, flags=re.IGNORECASE)
其思想是根据元素编号,将列表词_错误中的元素替换为列表词_确定中的相应元素。所以保护->利润,保护->盈利能力
例如:
a="prots went up"
b=fix_fibase(a)
print(b)
产出:profs上升
应该是利润上升了
但它不起作用。。。没有错误,但没有替换
有什么建议吗
万分感谢 您的代码工作正常,只需返回固定值: 输出:
profit is not evil
试试这个:
def fix_fibase(text):
word_wrong = ['prot', 'protability', 'protable', 'protably', 'prots']
word_ok = ['profit', 'profitability', 'profitable', 'profitably', 'profits']
dict_words = dict(
zip(word_wrong, word_ok)) # it will create a dictionary with wrong word as a key and correct one as a value
words = text.split(" ")
replaced_text = " ".join([dict_words.get(word.lower(), word) for word in words])
return replaced_text
print(fix_fibase("blah prot blah")) # output: blah profit blah
预期的输出是什么?你能举个例子吗?你说的“但不起作用”是什么意思?@Gabip,请只看一个单词的示例。其思想是根据元素编号,将列表中的一个元素替换为另一个列表中的对应元素。所以保护->利润,保护->利润,@MauriceMeyer没有错误,但文本中也没有任何更改…@PauloAlves和返回什么?在哪里替换?是否提供了一个文本来替换?
def fix_fibase(text):
word_wrong = ['prot', 'protability', 'protable', 'protably', 'prots']
word_ok = ['profit', 'profitability', 'profitable', 'profitably', 'profits']
dict_words = dict(
zip(word_wrong, word_ok)) # it will create a dictionary with wrong word as a key and correct one as a value
words = text.split(" ")
replaced_text = " ".join([dict_words.get(word.lower(), word) for word in words])
return replaced_text
print(fix_fibase("blah prot blah")) # output: blah profit blah