假设我有一个以下格式的输入文本文件:
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
文件本身很长,在我感兴趣的部分之间散布着许多无关的线。我不太确定如何在匹配的行之后直接指定打印线。
答案 0 :(得分:1)
# f is a file object
# n1 is how many lines to read
lines = [f.readline() for i in range(n1)]
答案 1 :(得分:0)
您可以将这样的逻辑放在生成器中:
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))