搜索其他文档中包含字符串的所有句子

2024-06-09 10:59:44 发布

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

我有一个包含200个单词的文件,每个单词都在一个新行上。 我想在另一个文件中搜索所有这些单词。我希望每个包含这些单词的句子都被打印出来。 现在,只出现第一个单词的匹配项。之后,它就停止了。在

corpus = open('C:\\Users\\Lucas\\Desktop\\HAIT\\Scriptie\\Tweet-corpus\\Corpus.txt', 'r', encoding='utf8')

with open('C:\\Users\\Lucas\\Desktop\\HAIT\\Scriptie\\Tweet-corpus\\MostCommon3.txt', 'r', encoding='utf8') as list:
for line in list:
    for a in corpus:
        if line in a:
            print(a)

Tags: 文件intxtcorpusopenutf8单词users
1条回答
网友
1楼 · 发布于 2024-06-09 10:59:44
# Prepare the list of words
word_file = open('wordfile', 'r', encoding='utf8')
words = [word.strip() for word in word_file.readlines()]
word_file.close()

# Now examine each sentence:
with open('sentencefile') as sentences:
    for sentence in sentences:
        found = False
        for word in words:
            if word in sentence:
                found = True
                break
        if found:
            print sentence

相关问题 更多 >