Skip to main content
 首页 » 编程设计

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

2025年05月04日38over140

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

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 都会根据字典键检查匹配项。如果存在与匹配项类似的键,那么它会将字符串中的键替换为该特定键的值。

如果没有找到 key ,如果您使用ColorPairs[m.group()],它会显示KeyError。所以我使用了 dict.get() 方法,如果没有找到键,它会返回一个默认值。

输出:

The red blue ball