简体   繁体   English

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

[英]Replacing words in text using dictionary

I am trying to create a program that replaces word from a string. 我正在尝试创建一个程序来替换字符串中的单词。

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'

This program replaces 'red' to 'blue', but not 'blue' to 'red'.I am stuck trying to figure out a way to make it so that the program doesn't override the first replaced key. 该程序将“红色”替换为“蓝色”,而不是“蓝色”替换为“红色”。

You could use re.sub function. 您可以使用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+ matches one or more non-space characters. \\S+匹配一个或多个非空格字符。 You could use \\w+ instead of \\S+ also. 您也可以使用\\w+代替\\S+ Here for each single match, python would check for the match against the dictionary key. 在这里,对于每个匹配项,python都会根据字典键检查匹配项。 If there is a key like the match then it would replace the key in the string with the value of that particular key. 如果存在像match这样的键,则它将用该特定键的值替换字符串中的键。

If there is no key found, it would display KeyError if you use ColorPairs[m.group()] . 如果没有钥匙上发现,它会显示KeyError ,如果你使用ColorPairs[m.group()] So that i used dict.get() method which returns a default value if there is no key found. 因此,我使用dict.get()方法,如果没有找到键,该方法将返回默认值。

Output: 输出:

The red blue ball

Since the dictionary is unordered, So It may take blue converted to red in the first iteration and in the second iteration it change again from red to blue . 由于字典是无序的,因此它可能需要在第一次迭代中将blue转换为red ,而在第二次迭代中,它又从redblue So in order to get the result you need to code in this manner. 因此,为了获得结果,您需要以这种方式进行编码。 This is certainly not the best Solution but an alternate way. 这当然不是最好的解决方案,而是另一种方法。

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')

If you don't want to use regex as suggested by @Avinash, you can split text into words, replace and then join. 如果您不想按@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')

output 输出

The blue and red ball

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM