使用Python中的字典搜索和替换

时间:2017-06-03 18:16:04

标签: python python-3.x

我有一本字典并使用它我正在搜索和替换工作。这是我的代码:

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

请帮我确定问题。

0 个答案:

没有答案