擅长:python、mysql、java
<pre><code>x = re.compile(a)
x.sub(b, c)
</code></pre>
<p>相当于</p>
<pre><code>re.sub(a, b, c)
</code></pre>
<p>也就是说,编译的regex <code>a</code>是<code>pattern</code>,<code>b</code>是替换<code>repl</code>,<code>c</code>是<code>string</code>。你知道吗</p>
<p>在这种情况下,<code>repl</code>是<em>函数</em>,<code>translate</code>。从<a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow">the docs</a>:</p>
<blockquote>
<p>If <em>repl</em> is a function, it is called for every non-overlapping occurrence of <em>pattern</em>. The function takes a single match object argument, and returns the replacement string.</p>
</blockquote>
<p><code>match</code>参数由<code>re.sub</code>为<code>string</code>中的每个匹配项提供,函数返回<code>worddict</code>中的适当替换项以替换为<code>txt</code>。你知道吗</p>
<p>你也可以这样写:</p>
<pre><code>return rc.sub(lambda match: worddict[match.group(0)], txt)
</code></pre>