Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从列表中替换子字符串的有效方法_Python_List_Replace_Similarity - Fatal编程技术网

Python 从列表中替换子字符串的有效方法

Python 从列表中替换子字符串的有效方法,python,list,replace,similarity,Python,List,Replace,Similarity,嗨,我有一个大文件保存为一个句子和一个专有名称列表,可能在文件中 我想用标签[PERSON]替换列表的实例 ex: sentence = "John and Marie went to school today....." list = ["Maria", "John"....] 结果=[人]和[人]今天上学了 正如你们所看到的,我仍然想抓住这个名字的变化,比如玛丽亚和玛丽,因为他们的拼写不同,但很接近 我知道我可以使用循环,但因为列表和句子都很大,所以可能有一种更有效的方法。谢谢您可以在输

嗨,我有一个大文件保存为一个句子和一个专有名称列表,可能在文件中

我想用标签[PERSON]替换列表的实例

ex: sentence = "John and Marie went to school today....."

list = ["Maria", "John"....]
结果=[人]和[人]今天上学了

正如你们所看到的,我仍然想抓住这个名字的变化,比如玛丽亚和玛丽,因为他们的拼写不同,但很接近

我知道我可以使用循环,但因为列表和句子都很大,所以可能有一种更有效的方法。谢谢

您可以在输入列表中使用,以匹配拼写变化的单词。例如,如果需要匹配Marie和Maria,可以使用Mari(e | a)作为正则表达式。以下是您可以使用的后续代码:

import re

mySentence = "John and Marie and Maria went to school today....."
myList = ["Mari(e|a)", "John"]

myNewSentence = re.compile("|".join(myList)).sub('[PERSON]', mySentence)

print(myNewSentence)  # [PERSON] and [PERSON] and [PERSON] went to school today.....
用于检查句子中的每个单词是否与姓名的单词紧密匹配(匹配百分比高于80%),如果是,则将其替换为
[PERSON]

>>> from fuzzywuzzy import process, fuzz
>>> names = ["Maria", "John"]
>>> sentence = "John and Marie went to school today....."
>>>
>>> match = lambda word: process.extractOne(word, names, scorer=fuzz.ratio, score_cutoff=80)
>>> ' '.join('[PERSON]' if match(word) else word  for word in sentence.split())
'[PERSON] and [PERSON] went to school today.....'

你需要将“不同但接近”的确切含义正式化请把你写的代码张贴下来,把你的问题缩小到其他用户能理解和回答的地方。从不同的角度来说,我的意思是拼写变体——你会如何把它正式化?我想很多人会认为“玛丽亚”和“玛丽”是不同的名字,因为它们不是同音异义词(它们在说话时听起来不同)。你也许能找到一组同音词的名字。