通过python在多个文本文件中查找搜索词

时间:2018-06-04 10:48:26

标签: python parsing search text

在一个文件夹中包含许多文本文件。如何在这些文件中找到搜索词(例如,某些词)以获得该搜索词所在文档的名称和路径文件?

我尝试了建议的修改方法,但它只显示文件夹中的第一个文件,而不是搜索术语:

dirname = '/Users/user/Documents/DataText/'
search_terms = ['elevator']

for f in os.listdir(dirname):

    text = open(os.path.join(dirname,f)) 

    text = [line.rstrip('\n') for line in f]

    if any([term in text for term in search_terms]):
        print (f)

1 个答案:

答案 0 :(得分:1)

import os

dirname = '/home/user/mydirectory'
search_terms = ['apple', 'banana', 'peach']

for f in os.listdir(dirname):
    text = '\n'.join( open(os.path.join(dirname,f)).readlines() )
    if any([term in text for term in search_terms]):
        print f