擅长:python、mysql、java
<p>在Python中最快的方法是使用字典查找句子中的每个单词,然后累加和关联的值。主数据结构可能如下所示:</p>
<pre><code>filters = {
"fox" : (
('uniqueid1', 'uniqueid2'),
('uniqueid3', 'uniqueid4'),
),
"fence" : (
('uniqueid5', 'uniqueid6'),
),
}
</code></pre>
<p>使用这种方式(在8位字符上):</p>
^{pr2}$
<p>或者,它可能会更快(是时候找出答案),这样可以避免双重字典查找:</p>
<pre><code>from string import punctuation
def map_words(sentence):
for word in sentence.translate(None, punctuation).split():
try:
yield filters[word]
except KeyError:
pass
sentence = 'The fluffy fox jumped the friggin fence.'
print [v for v in map_words(sentence)]
</code></pre>
<p>不管怎样,这就是输出:</p>
<pre class="lang-none prettyprint-override"><code>[(('uniqueid1', 'uniqueid2'), ('uniqueid3', 'uniqueid4')), (('uniqueid5', 'uniqueid6'),)]
</code></pre>