擅长:python、mysql、java
<p><code>re.sub</code>可以调用返回替换的函数</p>
<pre><code>segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'}
sentence = "this is a foobar in a barbar withoutspace"
import re
def fn(match):
return segmenter[match.group()]
print re.sub('|'.join(re.escape(k) for k in segmenter), fn, sentence)
</code></pre>