Python Re:覆盖问题
我在替换字符串的一部分时遇到问题。现在这个代码。我的目标是为这本字典中包含键的每个字符串Python Re:覆盖问题,python,regex,Python,Regex,我在替换字符串的一部分时遇到问题。现在这个代码。我的目标是为这本字典中包含键的每个字符串 mapping = { "St": "Street", "St.": "Street", 'Rd': 'Road', 'Rd.': 'Road', 'Ave': 'Avenue', 'Ave.': 'Avenue', 'Ln':'Lane',
mapping = { "St": "Street",
"St.": "Street",
'Rd': 'Road',
'Rd.': 'Road',
'Ave': 'Avenue',
'Ave.': 'Avenue',
'Ln':'Lane',
'Ln.':'Lane',
'Dr':'Drive',
'Dr.':'Drive',
'Pl':'Place',
'Pl.':'Place',
'Pkwy':'Parkway',
'Blvd.': 'Boulevard',
'Blvd': 'Boulevard'
}
用字典中的值替换字符串的该部分
street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE)
def update_name(name, mapping):
for key,value in mapping.iteritems():
if key in name:
newname = re.sub(street_type_re,value,name)
print name,'==>',newname
return name
现在代码正在做这样的事情
National Rd SW ==> National Rd Road
我需要把它修好,这样它就可以返回这个
National Rd SW ==> National Road SW
您可以简单地替换键
,而不是将其与预编译的regex或
newname = re.sub(r"\b"+key+r"\b",value,name)
您的将替换上一个,因为您有
$
这是否适用于部分字符串?例如:海德街==>海德街,州街==>斯特雷塔特街?@user3590113所以州
应该改为斯特雷塔特街
?不,我担心会发生这种情况。我知道你的回答掩盖了危险吗?我刚刚试过。事情就是这样。North High Street==>North High Street尽管你回答的第二部分有效,但我还是会给你的。
newname = re.sub(r"\b"+key+r"\b",value,name)