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

2024-10-02 12:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'

此程序将“red”替换为“blue”,但不会将“blue”替换为“red”。我一直在尝试找出一种方法,以便程序不会覆盖第一个替换的键。你知道吗


Tags: andthekey字符串textin程序for
3条回答

如果您不想按照@Avinash的建议使用regex,可以将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

因为字典是无序的,所以它可能需要在第一次迭代中将blue转换为red,在第二次迭代中它又从red转换为blue。所以为了得到结果,你需要以这种方式编码。这当然不是最好的解决办法,而是另一种办法。你知道吗

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')

您可以使用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都会根据dictionary键检查匹配。如果有一个类似match的键,那么它将用该特定键的值替换字符串中的键。你知道吗

如果找不到键,如果使用ColorPairs[m.group()],它将显示KeyError。所以我使用了dict.get()方法,如果找不到键,它将返回一个默认值。你知道吗

输出:

The red blue ball

相关问题 更多 >

    热门问题