在Python中使用字典进行搜索和替换

2024-07-05 10:20:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,我正在用它做搜索和替换的工作。这是我的密码:

import re

d = {
'non':'nonz',
'$non':'nonzz',
'non profit':'non profitz'
}

line1 = 'non non profit'
line2 = '$non non profit'

'''
The regex is constructed from all the keys by sorting them in descending 
order of length and joining them with the | regex alternation operator. 
The sorting is necessary so that the longest of all possible choices is 
selected if there are any alternatives.
'''
regex = re.compile(r'\b(' + '|'.join(re.escape(key) for key in sorted(d, key=len, reverse=True)) + r')\b')

line1 = regex.sub(lambda x: d[x.group()], line1)
line2 = regex.sub(lambda x: d[x.group()], line2)

print (line1) # nonz non profitz
print (line2) # $nonz non profitz
# line1 is being replaced correctly
# However, I am expecting line2 to be: nonzz non profitz
# i.e. I am expecting $non from line2 to be replaced with nonzz

请帮我找出问题所在。你知道吗


Tags: thekeyfromreisallregexnon