ワンピース...
:
import re
def generateMwR(wordDic):
rc = re.compile('|'.join(map(re.escape, wordDic)))
def f(text):
def translate(match):
print(match.group(0))
return wordDic[match.group(0)]
return rc.sub(translate, text)
return f
使い方は次のようになります
# Our dictionary
wordDic = {'hello': 'foo', 'hi': 'bar', 'hey': 'baz'}
# Escape every key in dictionary with regular expressions' escape character.
# Escaping is requred so that possible special characters in
# dictionary words won't mess up the regex
map(re.escape, wordDic)
# join all escaped key elements with pipe | to make a string 'hello|hi|hey'
'|'.join(map(re.escape, wordDic))
# Make a regular expressions instance with given string.
# the pipe in the string will be interpreted as "OR",
# so our regex will now try to find "hello" or "hi" or "hey"
rc = re.compile('|'.join(map(re.escape, wordDic)))
のでRCは今、辞書にある単語と一致し、rc.subは、指定された文字列内のそれらの単語を置き換えます。変換関数は、正規表現が一致を返すときに、キーの対応する値を返します。
[正規表現](https://docs.python.org/2/howto/regex.html)についてお読みください。 –
このような質問はどうすればよいですか?それは[正規表現が何を意味するか](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean)のような質問ではありませんが、それに似ています。 –