如何使用python library re.sub剥离文件的开头?

如何使用python library re.sub剥离文件的开头?,python,regex,substitution,Python,Regex,Substitution,我很高兴问我的第一个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

我很高兴问我的第一个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篇文章吗?

您可以使用来获得此效果

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

我真的不明白你想从你的代码中做什么。您是否正在尝试将“article:”的所有实例替换为“article”?在这里使用(
*
-->
*?
)会对您有所帮助。。此外,缺少替换部分
。。但是,如果文件较大,则不建议对整个文件进行slurping。。此外,您还可以使用
open('sample.txt').read()
而不是自定义loop哦,太好了,我用非贪婪的正则表达式进行了尝试,效果很好!!!!!!非常感谢Hanks的帮助itertools.dropwhile正在使用它。我不知道这个图书馆。Sundeep还给了我另一个解决方案:使用非贪婪表达式。谢谢你的帮助