用python中的字符串中的另一个单词替换单词

时间:2013-05-17 03:14:14

标签: python regex string replace

我有一个字符串:"y, i agree with u."

我有数组字典[(word_will_replace, [word_will_be_replaced])]

[('yes', ['y', 'ya', 'ye']), ('you', ['u', 'yu'])]

我想将 'y'替换为'yes' ,将 'u'替换为'you' 根据数组字典。

所以我想要的结果是:"yes, i agree with you."

我想在那里保留标点符号。

3 个答案:

答案 0 :(得分:3)

import re
s="y, i agree with u. yu."
l=[('yes', ['y', 'ya', 'ye']), ('you', ['u', 'yu'])] 
d={ k : "\\b(?:" + "|".join(v) + ")\\b" for k,v in l}
for k,r in d.items(): s = re.sub(r, k, s)  
print s

<强>输出

yes, i agree with you. you.

答案 1 :(得分:2)

Replacing substrings given a dictionary of strings-to-be-replaced as keys and replacements as values. Python扩展@ gnibbler的答案,并在评论中提供Raymond Hettinger提供的技巧。

import re
text = "y, i agree with u."
replacements = [('yes', ['y', 'ya', 'ye']), ('you', ['u', 'yu'])]
d = {w: repl for repl, words in replacements for w in words}
def fn(match):
    return d[match.group()]

print re.sub('|'.join(r'\b{0}\b'.format(re.escape(k)) for k in d), fn, text)

>>> 
yes, i agree with you.

答案 2 :(得分:0)

这不是字典 - 它是一个列表,但可以很容易地转换为dict。但是,在这种情况下,我会更清楚一点:

d = {}
replacements = [('yes', ['y', 'ya', 'ye']), ('you', ['u', 'yu'])]
for value,words in replacements:
    for word in words:
        d[word] = value

现在您已将字典映射到您想要替换它们的响应:

{'y':'yes', 'ya':'yes', 'ye':'yes',...}

一旦你有了这个,你可以使用正则表达式从这里弹出我的答案:https://stackoverflow.com/a/15324369/748858