我有字符串1km N of Piedmont, California
,我想用等效字(1
)替换距离值one
,但仅当数字低于10时(在这种情况下,它)是)。我还想将km
替换为kilometre
,N
替换为North
,E
替换为East
等。
最接近Pythonic的方式是什么?
答案 0 :(得分:1)
正则表达式替换应该可以很好地使用带字典查找的函数:
def replace(match):
d = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', 'N': 'North', 'E': 'East', 'S': 'South', 'W': 'West'}
source = match.group(1).strip()
return d.get(source, source) + ' '
text = '1km N of Piedmont, California'
print re.sub(r'(\d+ *(?=km)|[NESW]\s+(?=of))', replace, text)
这会显示如下内容:
one km North of Piedmont, California
更新 - 要处理kilometres
,脚本可以修改如下:
def convert(text):
def replace(match):
d = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', 'N': 'North', 'E': 'East', 'S': 'South', 'W': 'West'}
source = match.group(1).strip()
if 'km' in source:
source = source.split("km")[0].strip()
return "{} kilometre{}".format(d.get(source, source), '' if source == '1' else 's')
else:
return d.get(source, source) + ' '
return re.sub(r'(\d+ *km|[NESW]\s+(?=of))', replace, text)
print convert('1 km N of Piedmont, California')
print convert('1km N of China')
,并提供:
one kilometre North of Piedmont, California
one kilometre North of China