输入: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
我想将此实现转换为regex,因为此解决方案对我来说似乎有点混乱,并且偶尔会引起一些问题。我对regex并不是最好的,所以如果有人可以引导我朝正确的方向前进,将不胜感激!
这是我当前对regex实现的尝试:
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
我对正则表达式没有太多经验,所以请让我知道我所做的任何工作是否不正确,以及将“ th”添加到适当位置的最佳方法是什么。
谢谢。
仅一种方法,即找到一个数字后面和那些模式词之一之前的位置并放入'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'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句