1

すべてのキーが 3 文字の長さの辞書があります。threeLetterDict={'abc': 'foo', 'def': 'bar', 'ghi': 'ha' ...}

次に、文abcdefghiをに翻訳する必要がありfoobarhaます。で以下の方法を試していますがre.sub、辞書を入れる方法がわかりません:

p = re.compile('.{3}') # match every three letters
re.sub(p,'how to put dictionary here?', "abcdefghi")

ありがとう!(入力長が 3 の倍数かどうかを確認する必要はありません)

4

3 に答える 3

3

任意の callable をre.subに渡すことができるので、次のようになります。

p.sub(lambda m: threeLetterDict[m.group(0)], "abcdefghi")

できます!

于 2013-09-29T00:18:32.767 に答える