繁体   English   中英

使用字典替换文本中的单词

[英]Replacing words in text using dictionary

我正在尝试创建一个程序来替换字符串中的单词。

ColorPairs = {'red':'blue','blue':'red'}

def ColorSwap(text):
    for key in ColorPairs:
        text = text.replace(key, ColorPairs[key])
    print text

ColorSwap('The red and blue ball')
# 'The blue and blue ball'
instead of
# 'The blue and red ball'

该程序将“红色”替换为“蓝色”,而不是“蓝色”替换为“红色”。

您可以使用re.sub函数。

import re
ColorPairs = {'red':'blue','blue':'red'}
def ColorSwap(text):
    print(re.sub(r'\S+', lambda m: ColorPairs.get(m.group(), m.group()) , text))

ColorSwap('The blue red ball')

\\S+匹配一个或多个非空格字符。 您也可以使用\\w+代替\\S+ 在这里,对于每个匹配项,python都会根据字典键检查匹配项。 如果存在像match这样的键,则它将用该特定键的值替换字符串中的键。

如果没有钥匙上发现,它会显示KeyError ,如果你使用ColorPairs[m.group()] 因此,我使用dict.get()方法,如果没有找到键,该方法将返回默认值。

输出:

The red blue ball

由于字典是无序的,因此它可能需要在第一次迭代中将blue转换为red ,而在第二次迭代中,它又从redblue 因此,为了获得结果,您需要以这种方式进行编码。 这当然不是最好的解决方案,而是另一种方法。

import re
def ColorSwap(text):
    text = re.sub('\sred\s',' blue_temp ', text)
    text = re.sub('\sblue\s', ' red_temp ', text)
    text = re.sub('_temp','', text)
    return text

print ColorSwap('The red and blue ball')

如果您不想按@Avinash的建议使用正则表达式,则可以将text拆分为单词,然后替换然后合并。

ColorPairs = {'red':'blue','blue':'red'}
def ColorSwap(text):
    textList = text.split(' ')
    text = ' '.join(ColorPairs.get(k, k) for k in textList)
    print text

ColorSwap('The red and blue ball')

输出

The blue and red ball

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM