python - 使用python(acora)查找包含关键字的行

标签 python search aho-corasick

我正在编写一个程序,该程序读取文本文件目录并查找重叠的字符串的特定组合(即在所有文件之间共享)。我当前的方法是从此目录中获取一个文件,解析它,构建每个字符串组合的列表,然后在其他文件中搜索该字符串组合。例如,如果我有十个文件,我会读取一个文件,解析它,存储我需要的关键字,然后在其他九个文件中搜索该组合。我会对每个文件重复此操作(确保单个文件不会搜索自身)。为此,我尝试使用 python 的 acora模块。

到目前为止我的代码是:

def match_lines(f, *keywords):
    """Taken from [https://pypi.python.org/pypi/acora/], FAQs and Recipes #3."""
    builder = AcoraBuilder('\r', '\n', *keywords)
    ac = builder.build()

    line_start = 0
    matches = False
    for kw, pos in ac.filefind(f):  # Modified from original function; search a file, not a string.
        if kw in '\r\n':
            if matches:
                yield f[line_start:pos]
                matches = False
            line_start = pos + 1
        else:
            matches = True
    if matches:
        yield f[line_start:]


def find_overlaps(f_in, fl_in, f_out):
    """f_in: input file to extract string combo from & use to search other files.
    fl_in: list of other files to search against.
    f_out: output file that'll have all lines and file names that contain the matching string combo from f_in.
    """
    string_list = build_list(f_in)  # Open the first file, read each line & build a list of tuples (string #1, string #2). The "build_list" function isn't shown in my pasted code.
    found_lines = []  # Create a list to hold all the lines (and file names, from fl_in) that are found to have the matching (string #1, string #2).
    for keywords in string_list:  # For each tuple (string #1, string #2) in the list of tuples
        for f in fl_in:  # For each file in the input file list
            for line in match_lines(f, *keywords):
                found_lines.append(line)

正如您可能知道的那样,我使用了 acora 网页“常见问题解答和食谱”#3 中的函数 match_lines。我还在模式中使用它来解析文件(使用 ac.filefind()),也位于网页中。

该代码似乎可以工作,但它只是为我提供了具有匹配字符串组合的文件名。我想要的输出是从包含我的匹配字符串组合(元组)的其他文件中写出整行。

最佳答案

我没有看到这里会产生文件名,正如你所说的那样。

无论如何,要获取行号,您只需在在 match_lines() 中传递它们时对它们进行计数即可:

line_start = 0
line_number = 0
matches = False
text = open(f, 'r').read()
for kw, pos in ac.filefind(f):  # Modified from original function; search a file, not a string.
    if kw in '\r\n':
        if matches:
            yield line_number, text[line_start:pos]
            matches = False
        line_start = pos + 1
        line_number += 1
    else:
        matches = True
if matches:
    line_number, yield text[line_start:]

关于python - 使用python(acora)查找包含关键字的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48751629/

相关文章:

python - 按两个元素分组的数据帧统计信息

python - Pandas:如何按日期时间对组数据进行排序?

python - 如何从类型别名中确定类型?

javascript - 在最少的运行中有效地查找并返回多个值的数组位置

ruby-on-rails - 如何将整个单词与 Aho corasick 匹配?

python - UTF-8编码、字典查找

c++ - 在c++中找到两个 vector 中第一个公共(public)条目的位置的最快方法是什么?

css - Google 自定义搜索 (CSEv2) 对样式有帮助吗?

php - 更快的 Aho-Corasick PHP 实现

algorithm - aho corasick 算法的状态转移表