输入:1 10 avenue
所需输出:1 10th avenue
如上所示,我给出了一个输入示例,以及我想要的所需输出。基本上我需要查找有一个数字后跟某个模式(大道,街道等)的实例。我有一个包含所有模式的列表,它名为patterns
。
如果该号码没有" th"在它之后,我想添加" th"。只需添加" th"很好,因为我的代码的其他部分会将其更正为" st"," nd"," rd"如果有必要的话。
示例:
1 10th avenue
好的
1 10 avenue
不行,应该添加!
我已经实施了一个有效的解决方案:
def Add_Th(address):
try:
address = address.split(' ')
except AttributeError:
pass
for pattern in patterns:
try:
location = address.index(pattern) - 1
number_location = address[location]
except (ValueError, IndexError):
continue
if 'th' not in number_location:
new = number_location + 'th'
address[location] = new
address = ' '.join(address)
return address
我想将此实现转换为正则表达式,因为此解决方案对我来说似乎有些混乱,偶尔会导致一些问题。我不是最好的正则表达式,所以如果有人能引导我朝着正确的方向前进,我将不胜感激!
以下是我目前对正则表达式实现的尝试:
def add_th(address):
find_num = re.compile(r'(?P<number>[\d]{1,2}(' + "|".join(patterns + ')(?P<following>.*)')
check_th = find_num.search(address)
if check_th is not None:
if re.match(r'(th)', check_th.group('following')):
return address
else:
# this is where I would add th. I know I should use re.sub, i'm just not too sure
# how I would do it
else:
return address
我对正则表达式没有太多经验,所以如果我所做的任何工作都不正确,请告诉我,以及添加&#34;&#的最佳方法是什么? 34;到适当的地方。
感谢。
答案 0 :(得分:0)
只需一种方法,找到后面的位置,位于其中一个模式词之前,并将'th'
放入其中:
>>> address = '1 10 avenue 3 33 street'
>>> patterns = ['avenue', 'street']
>>>
>>> import re
>>> pattern = re.compile(r'(?<=\d)(?= ({}))'.format('|'.join(patterns)))
>>> pattern.sub('th', address)
'1 10th avenue 3 33th street'