私は文字列を持っています:"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."
句読点は残しておきたい。
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 の回答を拡張します。コメントで Raymond Hettinger から実装されたヒントを使用したPython 。
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