[英]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.