gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:57:12 26 4
gpt4 key购买 nike

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

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

关于python - 使用字典替换文本中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29001578/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com