我很高兴问我的第一个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篇文章吗?
答案 0 :(得分: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