我正在尝试创建一个程序来替换字符串中的单词。
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”。我被困在试图找出一种方法,以便程序不会覆盖第一个替换的键。
发布于 2015-03-12 11:57:36
你可以使用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将根据字典键检查匹配。如果存在类似于匹配的键,则它将用该特定键的值替换字符串中的键。
如果没有找到密钥,如果您使用ColorPairs[m.group()],则会显示KeyError。所以我使用了dict.get()方法,如果没有找到键,它会返回一个默认值。
输出:
The red blue ball发布于 2015-03-12 11:59:07
因为字典是无序的,所以它可能在第一次迭代中将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')发布于 2015-03-12 13:32:01
如果你不想像@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 ballhttps://stackoverflow.com/questions/29001578
复制相似问题