python中显示关键字所在行_使用python(acora)查找包含关键字的行

我正在写一个程序,它读取一个文本文件目录,然后找到一个重叠的字符串的特定组合(即在所有文件中共享)。我当前的方法是从这个目录中提取一个文件,解析它,建立一个每个字符串组合的列表,然后在其他文件中搜索这个字符串组合。例如,如果我有10个文件,我会读一个文件,解析它,存储我需要的关键字,然后在其他9个文件中搜索这个组合。我会对每个文件重复此操作(确保单个文件不会自行搜索)。为此,我尝试使用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)

你可能可以从网站上找到“食谱”和“常见问题解答”页面。我还在模式中使用它来解析文件(使用ac.filefind()),这些文件也位于网页中。在

代码似乎可以工作,但它只给我一个具有匹配字符串组合的文件名。我想要的输出是从包含匹配字符串组合(tuple)的其他文件中写出整行。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值