[英]Loop to run directory of .txt files
我想编写一个代码,在包含文本文件的大目录中运行 each.txt 文件。 我想打印出现输入词的上下文(即行)的每一次出现,以及文档的标题。
假设“猫”这个词出现在 5/10 文档中。 我想打印出现“猫”的每一个句子。
这是我到目前为止的代码。 它确实“有效”,但它只打印一个文档中输入单词的出现,而不是在每个文档中。
谢谢!
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 循环之外,如下所示:
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)
现在,相同的输入词将用于每个文档。 请参阅下面的示例 output 应用此更改(并在我的两个文本文件“t.txt”和“3.txt”中检测猫)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.