循环运行.txt文件的目录
我想编写一个代码来运行包含文本文件的大目录中的每个 .txt 文件。我想打印输入单词出现的上下文(即行)的每一次出现,以及文档的标题。
假设单词“cat”出现在 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)
I want to write a code that runs each .txt file in a large directory containing text files. I want to print every single occurrence of the context (i.e. line) in which the input word appears in, as well as the title of the document(s).
Let's say the word 'cat' appears in 5/10 documents. I want to print every single sentence in which 'cat' appears in.
Here's the code I have so far. It does "work", but it only prints the occurrence of the input word in one document, not in every single document.
Thank you!
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将输入单词的声明移到 for 循环之外,如下所示:
现在,每个文档将使用相同的输入单词。请参阅下面的示例输出,了解应用此更改的情况(并在我的两个文本文件“t.txt”和“3.txt”中检测cat)
You could move the declaration of the input word outside of the for-loop, like this:
Now the same input word will be used for each of the documents. See below for example output with this change applied (and detecting cat across my two text files "t.txt" and "3.txt")