[英]replacing word with another word from the string in python
我有一個字符串: "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."
: "yes, i agree with you."
我想在那里保留標點符號。
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.
從“ 替換子字符串”擴展了@gnibbler的答案,其中給出了要替換的字符串字典作為鍵,將替換字符串作為值。 Python和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.
那不是字典-而是列表,但是可以很容易地將其轉換成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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.