【问题标题】:Finding search terms in multiple text files via python通过python在多个文本文件中查找搜索词
【发布时间】:2018-06-04 10:48:25
【问题描述】:

在一个文件夹中有许多文本文件。我怎样才能在这些文件中找到搜索词(例如,某个词),从而获得该搜索词所在文档的名称和路径文件?

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

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)

【问题讨论】:

  • 你试过什么没用?

标签: python parsing search text


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-27
    • 2016-08-01
    • 2017-11-13
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多