如何使用 python 库 re.sub 删除文件的开头?

how to strip the beginning of a file with python library re.sub?

很高兴提出我的第一个 python 问题!!!我想去掉下面示例文件的开头部分(文章第一次出现之前的部分)。为此,我使用 re.sub 库。

下面是我的文件sample.txt:

fdasfdadfa
adfadfasdf
afdafdsfas
adfadfadf
adfadsf
afdaf

article: name of the first article
aaaaaaa
aaaaaaa
aaaaaaa
article: name of the first article
bbbbbbb
bbbbbbb
bbbbbbb
article: name of the first article
ccccccc
ccccccc
ccccccc

还有我的 Python 解析此文件的代码:

for line in open('sample.txt'):
    test = test + line

result = re.sub(r'.*article:', 'article', test, 1, flags=re.S)
print result

遗憾的是这段代码只显示最后一篇文章。代码输出:

article: name of the first article
ccccccc
ccccccc
ccccccc

有人知道如何只去除文件的开头并显示 3 篇文章吗?

你可以使用itertools.dropwhile来获得这个效果

from itertools import dropwhile

with open('filename.txt') as f:
    articles = ''.join(dropwhile(lambda line: not line.startswith('article'), f))

print(articles)

打印

article: name of the first article
aaaaaaa
aaaaaaa
aaaaaaa
article: name of the first article
bbbbbbb
bbbbbbb
bbbbbbb
article: name of the first article
ccccccc
ccccccc
ccccccc