检查一个字符串是否包含一组字符串的任何项?

2024-04-27 00:47:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,每行都有一个句子。我有一个单词表。我只想从列表中得到至少包含一个单词的句子。有没有一种Python式的方法?在


Tags: 方法列表单词句子文本文件单词表
3条回答

使用set.intersection

with open('file') as f:
    [line for line in f if set(line.lower().split()).itersection(word_set)]

或使用filter

^{pr2}$
sentences = [line for line in f if any(word in line for word in word_list)]

这里f将是您的file对象,例如,如果file.txt是文件名,并且它与脚本位于同一目录中,则可以将其替换为open('file.txt')。在

这将给你一个开始:

words = ['a', 'and', 'foo']
infile = open('myfile.txt', 'r')
match_sentences = []

for line in infile.readlines():
    # check for words in this line
    # if match, append to match_sentences list

相关问题 更多 >