使用替换词典替换字符串的最简单方法是什么?

时间:2010-03-08 10:08:23

标签: python regex

考虑..

dict = {
'Спорт':'Досуг',
'russianA':'englishA'
}

s = 'Спорт russianA'

我想用s中的各个dict值替换所有dict键。

7 个答案:

答案 0 :(得分:88)

使用re:

import re

s = 'Спорт not russianA'
d = {
'Спорт':'Досуг',
'russianA':'englishA'
}

pattern = re.compile(r'\b(' + '|'.join(d.keys()) + r')\b')
result = pattern.sub(lambda x: d[x.group()], s)
# Output: 'Досуг not englishA'

这只会匹配整个单词。如果您不需要,请使用模式:

pattern = re.compile('|'.join(d.keys()))

请注意,在这种情况下,如果某些字典条目是其他字典条目的子字符串,则应按长度对字词进行排序。

答案 1 :(得分:21)

您可以使用reduce功能:

reduce(lambda x, y: x.replace(y, dict[y]), dict, s)

答案 2 :(得分:17)

解决方案found here(我喜欢它的简单性):

def multipleReplace(text, wordDict):
    for key in wordDict:
        text = text.replace(key, wordDict[key])
    return text

答案 3 :(得分:5)

单向,无需重新

d = {
'Спорт':'Досуг',
'russianA':'englishA'
}

s = 'Спорт russianA'.split()
for n,i in enumerate(s):
    if i in d:
        s[n]=d[i]
print ' '.join(s)

答案 4 :(得分:3)

与ghostdog74差不多,虽然是独立创建的。一个区别, 使用d.get()代替d []可以处理不在dict中的项目。

>>> d = {'a':'b', 'c':'d'}
>>> s = "a c x"
>>> foo = s.split()
>>> ret = []
>>> for item in foo:
...   ret.append(d.get(item,item)) # Try to get from dict, otherwise keep value
... 
>>> " ".join(ret)
'b d x'

答案 5 :(得分:1)

我在类似的情况下使用过这个(我的字符串都是大写的):

def translate(string, wdict):
    for key in wdict:
        string = string.replace(key, wdict[key].lower())
    return string.upper()

希望以某种方式帮助......:)

答案 6 :(得分:1)

如果密钥有空间,则警告它失败,这是一个类似于ghostdog74和extaneons答案的压缩解决方案:

d = {
'Спорт':'Досуг',
'russianA':'englishA'
}

s = 'Спорт russianA'

' '.join(d.get(i,i) for i in s.split())