我正在尝试创建一个程序来替换字符串中的单词。你知道吗
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”。我一直在尝试找出一种方法,以便程序不会覆盖第一个替换的键。你知道吗
如果您不想按照@Avinash的建议使用regex,可以将
text
拆分为单词,替换然后加入。你知道吗输出
因为字典是无序的,所以它可能需要在第一次迭代中将
blue
转换为red
,在第二次迭代中它又从red
转换为blue
。所以为了得到结果,你需要以这种方式编码。这当然不是最好的解决办法,而是另一种办法。你知道吗您可以使用
re.sub
函数。你知道吗\S+
匹配一个或多个非空格字符。也可以使用\w+
而不是\S+
。在这里,对于每个匹配,python都会根据dictionary键检查匹配。如果有一个类似match的键,那么它将用该特定键的值替换字符串中的键。你知道吗如果找不到键,如果使用
ColorPairs[m.group()]
,它将显示KeyError
。所以我使用了dict.get()
方法,如果找不到键,它将返回一个默认值。你知道吗输出:
相关问题 更多 >
编程相关推荐