2024-04-27 00:47:18 发布
网友
我有一个文本文件,每行都有一个句子。我有一个单词表。我只想从列表中得到至少包含一个单词的句子。有没有一种Python式的方法?在
使用set.intersection:
set.intersection
with open('file') as f: [line for line in f if set(line.lower().split()).itersection(word_set)]
或使用filter:
filter
sentences = [line for line in f if any(word in line for word in word_list)]
这里f将是您的file对象,例如,如果file.txt是文件名,并且它与脚本位于同一目录中,则可以将其替换为open('file.txt')。在
f
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
使用
set.intersection
:或使用
^{pr2}$filter
:这里
f
将是您的file对象,例如,如果file.txt
是文件名,并且它与脚本位于同一目录中,则可以将其替换为open('file.txt')
。在这将给你一个开始:
相关问题 更多 >
编程相关推荐