使用正则表达式删除相对行

时间:2016-01-31 17:48:11

标签: python regex python-2.7

使用pdftotext创建了一个包含源pdf页脚的文本文件。页脚阻碍了需要完成的其他解析。页脚的格式如下:

This is important text.

9
Title 2012 and 2013

\fCompany
Important text begins again.

公司的行是唯一一个不会在文件中的其他地方重复出现的行。它显示为\x0cCompany\n。我想搜索这一行,并根据\x0cCompany\n出现的位置删除它和前三行(页码,标题和空行)。这就是我到目前为止所做的:

report = open('file.txt').readlines()
data = range(len(report))
name = []

for line_i in data:
    line = report[line_i]

    if re.match('.*\\x0cCompany', line ):
        name.append(report[line_i])

print name

这允许我创建一个列表,存储哪些行号出现这种情况,但我不明白如何删除这些行以及前面三行。看来我需要根据这个循环创建一些其他的循环,但我不能让它工作。

1 个答案:

答案 0 :(得分:2)

不是迭代并获取要删除的行的索引,而是遍历行并仅追加要保留的行。

迭代实际的文件对象,而不是将它们全部放在一个列表中也会更有效:

keeplines = []

with open('file.txt') as b:
    for line in b:
        if re.match('.*\\x0cCompany', line):
            keeplines = keeplines[:-3] #shave off the preceding lines
        else:
            keeplines.append(line)


file = open('file.txt', 'w'):
    for line in keeplines:
        file.write(line)