Python如何在匹配后获取一定数量的行

2024-04-19 04:54:56 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个以下格式的输入文本文件:

Section1 Heading    Number of lines: n1
Line 1
Line 2
...
Line n1
Maybe some irrelevant lines

Section2 Heading    Number of lines: n2
Line 1
Line 2
...
Line n2

其中文件的某些部分以指定该部分中有多少行的标题行开头。每个节标题都有不同的名称。

我已经编写了一个正则表达式,它将根据用户搜索每个部分的标题名称来匹配标题行,对其进行解析,然后返回数字n1/n2/etc,告诉我该部分有多少行。我一直在尝试使用for in循环来读取每一行,直到计数器到达n1,但到目前为止还没有成功。

这里是我的问题:当匹配中给定了匹配行的行数,并且每个部分的行数不同时,我如何返回匹配行后面的特定行数?我是编程新手,我很感激你的帮助。

编辑:好的,这是我目前掌握的相关代码:

import re
print
fname = raw_input("Enter filename: ")
toolname = raw_input("Enter toolname: ")

def findcounter(fname, toolname):
        logfile = open(fname, "r")

        pat = 'SUCCESS Number of lines :'
        #headers all have that format
        for line in logfile:
                if toolname in line:
                    if pat in line:
                            s=line

        pattern = re.compile(r"""(?P<name>.*?)     #starting name
                             \s*SUCCESS        #whitespace and success
                             \s*Number\s*of\s*lines  #whitespace and strings
                             \s*\:\s*(?P<n1>.*)""",re.VERBOSE)
        match = pattern.match(s)
        name = match.group("name")
        n1 = int(match.group("n1"))
        #after matching line, I attempt to loop through the next n1 lines
        lcount = 0
        for line in logfile:
             if line == match:
                    while lcount <= n1:
                                match.append(line)
                                lcount += 1
                                return result

文件本身很长,在我感兴趣的部分之间散布着许多不相关的行。我不太确定的是如何指定直接在匹配行之后打印行。


Tags: ofnameinre标题numberformatch
2条回答
# f is a file object
# n1 is how many lines to read
lines = [f.readline() for i in range(n1)]

你可以把这样的逻辑放在生成器中:

def take(seq, n):
    """ gets n items from a sequence """
    return [next(seq) for i in range(n)]

def getblocks(lines):
    # `it` is a iterator and knows where we are in the list of lines.
    it = iter(lines)
    for line in it:
        try:
            # try to find the header:
            sec, heading, num = line.split()
            num = int(num)
        except ValueError:
            # didnt work, try the next line
            continue

        # we got a header, so take the next lines
        yield take(it, num) 

#test
data = """
Section1 Heading  3
Line 1
Line 2
Line 3

Maybe some irrelevant lines

Section2 Heading 2
Line 1
Line 2
""".splitlines()

print list(getblocks(data))

相关问题 更多 >