python - 如何更快地在文本文件中搜索字符串

标签 python pandas

我想在数千个文本文件(可能有多达 100k 个文本文件,每个文本文件的大小从 1 KB 到 100 MB 不等)中搜索字符串列表(列表中有 2k 到 10k 个字符串)保存在一个文件夹并为匹配的文本文件名输出一个 csv 文件。

我已经开发了一个代码来完成所需的工作,但是在大约 2.5 GB 大小的大约 2000 个文本文件中搜索 2000 个字符串需要大约 8-9 个小时。

此外,使用这种方法会消耗系统内存,因此有时需要将 2000 个文本文件拆分成较小的批处理才能运行代码。

代码如下(Python 2.7)

# -*- coding: utf-8 -*-
import pandas as pd
import os

def match(searchterm):
    global result
    filenameText = ''
    matchrateText = ''
    for i, content in enumerate(TextContent):
        matchrate = search(searchterm, content)
        if matchrate:
            filenameText += str(listoftxtfiles[i])+";"
            matchrateText += str(matchrate) + ";"
    result.append([searchterm, filenameText, matchrateText])


def search(searchterm, content):
    if searchterm.lower() in content.lower():
        return 100
    else:
        return 0


listoftxtfiles = os.listdir("Txt/")
TextContent = []
for txt in listoftxtfiles:
    with open("Txt/"+txt, 'r') as txtfile:
        TextContent.append(txtfile.read())

result = []
for i, searchterm in enumerate(searchlist):
    print("Checking for " + str(i + 1) + " of " + str(len(searchlist)))
    match(searchterm)

df=pd.DataFrame(result,columns=["String","Filename", "Hit%"])

下面的示例输入。

字符串列表 -

["Blue Chip", "JP Morgan Global Healthcare","Maximum Horizon","1838 Large Cornerstone"]

文本文件 -

包含由\n 分隔的不同行的普通文本文件

下面的示例输出。

String,Filename,Hit%
JP Morgan Global Healthcare,000032.txt;000031.txt;000029.txt;000015.txt;,100;100;100;100;
Blue Chip,000116.txt;000126.txt;000114.txt;,100;100;100;
1838 Large Cornerstone,NA,NA
Maximum Horizon,000116.txt;000126.txt;000114.txt;,100;100;100;

如上例所示,第一个字符串在 4 个文件中匹配(以 ; 分隔),第二个字符串在 3 个文件中匹配,第三个字符串在任何文件中均未匹配。

有没有不拆分文本文件的更快搜索方式?

最佳答案

您的代码会在内存中大量推送大量数据,因为您将所有文件加载到内存中,然后搜索它们。

撇开性能不谈,您的代码可能需要一些清理工作。尝试尽可能自主地编写函数,而不依赖于全局变量(用于输入或输出)。

我使用列表理解重写了您的代码,它变得更加紧凑。

# -*- coding: utf-8 -*-
from os import listdir
from os.path import isfile

def search_strings_in_files(path_str, search_list):
    """ Returns a list of lists, where each inner list contans three fields:
    the filename (without path), a string in search_list and the
    frequency (number of occurences) of that string in that file"""

    filelist = listdir(path_str)

    return [[filename, s, open(path_str+filename, 'r').read().lower().count(s)]
        for filename in filelist
            if isfile(path_str+filename)
                for s in [sl.lower() for sl in search_list] ]

if __name__ == '__main__':
    print search_strings_in_files('/some/path/', ['some', 'strings', 'here'])

我在此代码中使用的机制:

阅读列表理解的提示:尝试从下到上阅读它,所以:

  • 我使用列表理解将 search_list 中的所有项目转换为 lower。
  • 然后我遍历该列表(for s in...)
  • 然后我使用复合语句 (if isfile...) 过滤掉不是文件的目录条目
  • 然后我遍历所有文件(for filename...)
  • 在顶行,我创建了包含三个项目的子列表:
    • 文件名
    • s,即小写搜索字符串
    • 打开文件的方法链调用,读取其所有内容,将其转换为小写并计算 s 的出现次数。

此代码使用了“标准”Python 函数中的所有功能。如果您需要更高的性能,您应该查看专门的库来完成这项任务。

关于python - 如何更快地在文本文件中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45122230/

相关文章:

python - 不在 Python 中执行的函数

Python Pydantic 错误 : TypeError: __init__() takes exactly 1 positional argument (2 given)

python - 如何有效地迭代 Pandas 数据帧的连续 block

python - 如何选择两个日期时间之间的数据框行?

python - 我实现的 Bowyer-Watson Delaunay 三角剖分不会删除包含超三角形点的三角形

python - 使用行和列值插入缺失值

python - 使用列中的值对 pandas 数据框进行多索引

python - 如何使用 Python 检查 Pandas 值是否为空或零

python-3.x - 使用数据帧作为输入并行化函数

python - Scikit-learn 混淆矩阵