replacing word with another word from the string i

2019-08-06 14:51发布

I have a string: "y, i agree with u."

And I have array dictionary [(word_will_replace, [word_will_be_replaced])]:

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

i want to replace 'y' with 'yes' and 'u' with 'you' according to the array dictionary.

So the result i want: "yes, i agree with you."

I want to keep the punctuation there.

3条回答
放我归山
2楼-- · 2019-08-06 15:16

Extending @gnibbler's answer from Replacing substrings given a dictionary of strings-to-be-replaced as keys and replacements as values. Python with the tips implemented from Raymond Hettinger in the comments.

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.
查看更多
我命由我不由天
3楼-- · 2019-08-06 15:24

That's not a dictionary -- it's a list, but it could be converted to a dict pretty easily. In this case, however, I would make it a little more explicit:

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

Now you have the dictionary mapping responses to what you want to replace them with:

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

once you have that, you can pop in my answer from here using regular expressions: https://stackoverflow.com/a/15324369/748858

查看更多
\"骚年 ilove
4楼-- · 2019-08-06 15:42
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

Output

yes, i agree with you. you.
查看更多
登录 后发表回答