您无法测试字符串中是否存在列表。您可以做的是测试另一个字符串中是否存在一个字符串。
lines = ['this is a line without any keywords',
'this is a line with one',
'this is a line with one and two',
'this is a line with three']
keywords = ['one', 'two', 'three']
for line in lines:
for word in keywords:
if word in line:
print(line)
break
The break
当第一个单词匹配时,有必要打破“单词”循环。否则它将打印它匹配的每个单词的行。
正则表达式解决方案也有同样的问题。您可以使用与上面相同的解决方案,并在单词上添加一个额外的循环,或者您可以构建一个将自动匹配任何单词的正则表达式。请参阅Python 正则表达式语法 https://docs.python.org/3.4/library/re.html文档。
for line in lines:
matches = re.findall('one|two|three', line)
if matches:
print(line, len(matches))
注意re.findall
如果没有匹配项,则返回一个空列表;如果有匹配项,则返回所有匹配项的列表。因此我们可以直接在 if 条件下测试结果,因为空列表的计算结果为False
.
您还可以轻松生成这些简单情况的正则表达式模式:
pattern = '|'.join(keywords)
print(pattern)
# 'one|two|three'
要对它们进行排序,您只需将它们放入元组列表中并使用key
的论证sorted
.
results = []
for line in lines:
matches = re.findall('one|two|three', line)
if matches:
results.append((line, len(matches)))
results = sorted(results, key=lambda x: x[1], reverse=True)
您可以阅读文档 https://docs.python.org/3.4/library/functions.html#sorted for sorted
,但是key
argument 提供了一个用于排序的函数。在本例中,我们提取每个元组的第二个元素,这是我们存储该行中匹配项数量的位置,并用它对列表进行排序。
您可以通过这种方式将其应用到实际文件并保存结果。
keywords = ['one', 'two', 'three']
pattern = '|'.join(keywords)
results = []
with open('myfile.txt', 'r') as f:
for line in f:
matches = re.findall(pattern, line)
if matches:
results.append((line, len(matches)))
results = sorted(results, key=lambda x: x[1], reverse=True)
with open('results.txt', 'w') as f:
for line, num_matches in results:
f.write('{} {}\n'.format(num_matches, line))
您可以阅读与上下文管理器 https://docs.python.org/3.4/reference/compound_stmts.html#the-with-statement,但在这种情况下,它基本上确保您在完成文件后将其关闭。