<p><em>根据您的评论编辑。</em></p>
<p>这可能就是你想要的:</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python
def find_best_letter_matches(lines, target):
m = []
m_count = 0
for line in lines:
count = sum(map(lambda x: x[0] == x[1], zip(line, target)))
if count > m_count:
m = []
m_count = count
if count == m_count:
m.append(line)
return m
def find_n_letter_matches(lines, target, n):
m = []
for line in lines:
count = sum(map(lambda x: x[0] == x[1], zip(line, target)))
if count >= n:
m.append(line)
return m
if __name__ == '__main__':
with open('text.txt', 'r') as f:
lines = f.read().split('\n')
best_matches = find_best_letter_matches(lines, 'bubal')
n_matches = find_n_letter_matches(lines, 'bubal', 2)
print('Best letter matches', best_matches)
print('At least 2 letters match', n_matches)
</code></pre>
<p>函数将每一行与目标进行逐字母比较,并计算匹配数。第一个返回最高匹配行的列表,第二个返回所有与<code>n</code>或更多字母匹配的行。你知道吗</p>
<p>示例文本(添加bubal)的输出是:</p>
<pre><code>Best letter matches ['bubal']
At least 2 letters match ['bulks', 'bible', 'bubal']
</code></pre>