[英]Python: Why is re.sub not replacing dict key with dict value when there is ',' in dict key
有点像这里的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
的字典中的键替换为该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
,在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)
解决问题的棘手解决方案。
我想我看到了这个问题。 逗号不被视为“单词字符”。 因此,在字符串'但是'中,逗号实际上将被视为结束字边界,而不是它后面的空格。 由于这种混淆,您通过使用单词边界快捷键“\\ b”定义的正则表达式模式与该单词不匹配。
如果你用\\ W(对于非单词字符)替换最后的\\ b,它会以你想要的方式工作吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.