循环到 .txt 文件的 运行 目录

Loop to run directory of .txt files

我想编写一个代码来运行包含文本文件的大目录中的每个 .txt 文件。我想打印出现输入词的上下文(即行)的每一次出现,以及文档的标题。

假设单词 'cat' 出现在 5/10 文档中。我想打印出现 'cat' 的每一个句子。

这是我目前的代码。它确实“有效”,但它只打印在一个文档中出现的输入词,而不是在每个文档中。

谢谢!

import os
import re


dir1=("/my directory/")

for txt in os.listdir(dir1):
    with open (dir1+"/"+txt, "r", encoding="utf8") as f_obj:
        contents=f_obj.readlines()
        word=input("Type the word whose context you want to find:")
        for line in contents:
            if re.search(word,line):
                print("Title of document:", f_obj.name)
                print("Context of use:", line)    

您可以将输入词的声明移到 for-loop 之外,如下所示:

import os
import re


dir1=("/my directory/")

word=input("Type the word whose context you want to find:")

for txt in os.listdir(dir1):
    with open (dir1+"/"+txt, "r", encoding="utf8") as f_obj:
        contents=f_obj.readlines()
        for line in contents:
            if re.search(word,line):
                print("Title of document:", f_obj.name)
                print("Context of use:", line)    

现在每个文档将使用相同的输入词。请参阅下面的应用此更改的示例输出(并在我的两个文本文件“t.txt”和“3.txt”中检测 cat

Type the word whose context you want to find:cat
Title of document: /my directory/t.txt
Context of use: cat on a bat

Title of document: /my directory/t.txt
Context of use: bat on a cat

Title of document: /my directory/3.txt
Context of use: cat on a bat

Title of document: /my directory/3.txt
Context of use: cat on a mat