特定字符串替换

时间:2015-08-29 07:04:45

标签: python regex

我有字符串1km N of Piedmont, California,我想用等效字(1)替换距离值one,但仅当数字低于10时(在这种情况下,它)是)。我还想将km替换为kilometreN替换为NorthE替换为East等。

最接近Pythonic的方式是什么?

1 个答案:

答案 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