我有一个关键字列表
Animals = ['dogs' , 'cat' , 'bird' ....]我有一个包含许多文件的目录,这些文件可能会出现一个或多个关键字。
File1.txt
“
File2.txt
“
我想搜索目录中的每个文件,并检查我的动物列表中的所有事件。我要记录fileName,行号,匹配,行。
期望输出的示例:
”
这个是可能的吗?Python是正确的工具吗?我已经能够使用python运行一些regex测试,但是我在访问特定的行号、匹配和行时遇到了困难。
import os
import re
words = ['dog' , 'cat' , 'bird' ]
rx = re.compile('|'.join(words), re.I)
for root, dirs, files in os.walk('C:\\MySearchDirectory\\'):
for filename in files:
if filename.endswith('.txt'):
with open(root + filename) as df:
data = df.read()
for match in rx.finditer(data):
print(filename + ' , ' + str(match) + ' , ' + str(match.span()))发布于 2021-05-25 14:58:32
当Python的标准in操作符完成任务时,不需要使用正则表达式,IMO:
import os
words = ['dog', 'cat', 'bird']
for root, _, files in os.walk(r'C:\MySearchDirectory'):
for path in filter(lambda p: p.endswith('.txt'), files):
with open(os.path.join(root, path)) as f:
for i, line in enumerate(f.readlines()):
for word in filter(lambda w: w in line, words):
print(f'{path}, {i+1}, {word}, {line.strip()}')使用filter对循环中的if进行列表理解是一个品味问题,但在这种情况下,我认为这是最简单的选择,因为它使两个过滤条件(文件需要以.txt结尾,字词需要出现在行中)很容易一眼就看出来。
输出:
File1.txt, 2, cat, "I'm a cat, I go meow"
File1.txt, 3, dog, "I'm a dog, I go woof"
File2.txt, 2, bird, "I'm a bird, I go tweet"发布于 2021-05-25 15:19:17
你可以这样做:
from pathlib import Path
def find_occurrences(file, any_word:list) -> list:
occurrences = []
with open(file, 'r') as f:
text = f.read()
lines = text.split('\n')
for line_number, line in enumerate(lines, start=1):
matched_words = [word for word in any_word if word in line]
if matched_words:
occurrence = {
"file": file,
"line_number": line_number,
"line": line,
"matched_words": matched_words
}
occurrences.append(occurrence)
return occurrences
occurrences = []
for file in Path(r"C:\\MySearchDirectory\\").glob("**/*.txt"):
occurrences += find_occurrences(file, any_word=["cat", "dog"])
occurrences首先,我们循环目录中的所有".txt“文件,并对每个文件执行函数find_occurrences。此函数返回事件列表,并使用该列表更新最终结果。函数本身只读取一个文件,遍历文件的每一行,检查每一行是否包含指定的单词,如果包含指定的单词,则存储结果。
返回的字典列表的结构如下:
[
{
'file': 'C:\\MySearchDirectory\\subdir\\file1.txt',
'line_number': 5,
'matched_words': ['cat', 'dog'],
'line': 'meau cat, hau hau dog'
},
...
]如果您需要更多的东西,只需调整发生字典。注意,line_number从一个开始。这似乎是这个例子的意图。
https://stackoverflow.com/questions/67690357
复制相似问题