首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用字典替换文本中的单词

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

Stack Overflow用户
提问于 2015-03-12 11:53:28
回答 3查看 146关注 0票数 1

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

代码语言:javascript
复制
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”。我被困在试图找出一种方法,以便程序不会覆盖第一个替换的键。

EN

回答 3

Stack Overflow用户

发布于 2015-03-12 11:57:36

你可以使用re.sub函数。

代码语言:javascript
复制
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()方法,如果没有找到键,它会返回一个默认值。

输出:

代码语言:javascript
复制
The red blue ball
票数 5
EN

Stack Overflow用户

发布于 2015-03-12 11:59:07

因为字典是无序的,所以它可能在第一次迭代中将blue转换为red,在第二次迭代中再次从red更改为blue。因此,为了获得结果,您需要以这种方式编写代码。这当然不是最好的解决方案,而是另一种方法。

代码语言:javascript
复制
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')
票数 0
EN

Stack Overflow用户

发布于 2015-03-12 13:32:01

如果你不想像@Avinash建议的那样使用正则表达式,你可以将text拆分成单词,替换,然后加入。

代码语言:javascript
复制
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')

输出

代码语言:javascript
复制
The blue and red ball
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29001578

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档