这里有点像 python/编程新手。首先,代码:
import re
patt_list = ['However,', 'phenomenal', 'brag']
dictionary = {'phenomenal': 'phenomenal|extraordinary|remarkable|incredible', 'However,': 'However,|Nevertheless,|Nonetheless,', 'brag': 'brag|boast'}
def replacer_factory1(dictionary):
def replacing(match):
if len(dictionary) > 0:
word = match.group()
exchange = dictionary.get(word, word)
spintax = '{' + exchange + '}'
create_place_holder = spintax.replace(' ', '#!#')
return create_place_holder
else:
return ""
return replacing
def replacing1(text):
regex_patt_list = r'\b(?:' + '|'.join(patt_list) + r')\b'
replacer = replacer_factory1(dictionary)
return re.sub(regex_patt_list, replacer, text)
with open('test_sent.txt', 'r+') as sent:
read_sent = sent.read()
sent.seek(0)
sent.write(replacing1(read_sent))
所以我在这里创建的代码在文本文件 test_sent.txt
中搜索我在名为 patt_list
的列表中的单词。如果单词在文本文件中,则使用 re.sub 将名为 dictionary
的字典中的键替换为该字典中的相应值,然后将这些更改写回文本文件。 (这段代码实际上是一个更大的脚本的一部分,其中字典的键是从 patt_list
创建的,以防万一你想知道为什么这里需要 patt_list
完全没有)。
但是,我在使用这段代码时遇到的问题是字典键 However,
没有替换为相应的值 However,|Nevertheless,|Nonetheless,
-而其余的键:值替换工作正常,并写入文本文件。
我相信可能是 However,
中的逗号导致了这个问题,因为我尝试了另一个键:键末尾带有逗号的值,但这也不起作用。
谁能告诉我为什么会这样?
运行代码之前“test_sent.txt”的内容:
Quite phenomenal. However, nothing to brag about?
运行代码后'test_sent.txt'的内容:
Quite {phenomenal|extraordinary|remarkable|incredible}. However, nothing to {brag|boast} about?
我实际上希望输出看起来像:
Quite {phenomenal|extraordinary|remarkable|incredible}. {However,|Nevertheless,|Nonetheless,} nothing to {brag|boast} about bragg's vinegar?
我不想要的(bragg's
的部分匹配):
Quite {phenomenal|extraordinary|remarkable|incredible}. {However,|Nevertheless,|Nonetheless,} nothing to {brag|boast} about {brag|boast}g's vinegar?
编辑:为了回应下面“WKPLUS”的有用回答,从 regex_patt_list
末尾删除 \b
在这里有效,但不是为了更大的用途我有这个代码。字典在现实中要大得多,所以当 \b
被删除时,我在文本中得到部分匹配,这是我不想要的。我更新了 test_sent.txt
以在末尾添加单词 bragg's vinegar
以说明删除 \b
时的部分匹配问题。
最佳答案
删除 regex_patt_list 中的第二个“\b”将解决您的问题。
def replacer_factory1(dictionary):
def replacing(match):
if len(dictionary) > 0:
word = match.group()[:-1]
exchange = dictionary.get(word, word)
spintax = '{' + exchange + '}'
create_place_holder = spintax.replace(' ', '#!#')
return create_place_holder + match.group()[-1]
else:
return ""
return replacing
def replacing1(text):
regex_patt_list = r'\b(?:' + '|'.join(patt_list) + r')\W'
replacer = replacer_factory1(dictionary)
return re.sub(regex_patt_list, replacer, text)
针对您的问题的棘手解决方案。
关于Python:当字典键中有 ',' 时,为什么 re.sub 不将字典键替换为字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20768783/