使用python(acora)查找包含关键字的行
我正在编写一个程序,在一个文本文件目录中读取并查找重叠字符串的特定组合(即在所有文件之间共享)。我目前的方法是从这个目录中提取一个文件,解析它,构建每个字符串组合的列表,然后在其他文件中搜索这个字符串组合。例如,如果我有十个文件,我会读取一个文件,解析它,存储我需要的关键字,然后搜索其他九个文件,寻找这个组合。我会对每个文件重复这一点(确保单个文件不会自行搜索)。为此,我尝试使用python的模块 到目前为止,我的代码是:使用python(acora)查找包含关键字的行,python,search,aho-corasick,Python,Search,Aho Corasick,我正在编写一个程序,在一个文本文件目录中读取并查找重叠字符串的特定组合(即在所有文件之间共享)。我目前的方法是从这个目录中提取一个文件,解析它,构建每个字符串组合的列表,然后在其他文件中搜索这个字符串组合。例如,如果我有十个文件,我会读取一个文件,解析它,存储我需要的关键字,然后搜索其他九个文件,寻找这个组合。我会对每个文件重复这一点(确保单个文件不会自行搜索)。为此,我尝试使用python的模块 到目前为止,我的代码是: def match_lines(f, *keywords): "
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()
),同样位于网页上
代码似乎可以工作,但它只生成具有匹配字符串组合的文件名。我想要的输出是从包含匹配字符串组合(tuple)的其他文件中写出整行内容。我不知道这里会产生什么文件名,正如您所说的那样 无论如何,要获得行号,只需在match_lines()中传递行号时对其进行计数:
“我不知道这里会产生什么文件名,就像你说的那样。”:显然你是对的。我在我知道有匹配字符串的两个文件上再次测试了我的原始代码,其中只有一个作为文件名返回。显然,使
甚至产生匹配文件名的代码不起作用。你知道如何修复这个部分吗(因为如果python没有找到包含我要查找的字符串的正确文件,我甚至无法测试行号的匹配)。我没有看到任何理论上可能产生文件名的代码。我只看到代码可以产生匹配行的内容:yield f[line_start:pos]抱歉回复太晚;我出城了。我的问题是,即使是产量f[line\u start:pos]
也不起作用;我没有得到包含匹配关键字的文件的完整行。你得到了什么?哦。我假设f是一个文件的内容。如果f只是文件名,这不可能,是的。看看“文件查找”是如何工作的,我现在更了解它了。您需要实际读取该文件才能返回其部分内容,我将更新我的答案。
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:]