好的,所以。这个有点烦人。我有一个包含多个"部分"的文件。该文件可能如下所示:
"""
Begin presentation. Welcome the new guest. Do this, do that
[+] Start group 1
+derrek
+bob
+james
+harry
[+] Start group 2
+Will
+Paul
+Mark
+Eric
Hello and welcome to this years presentation of the "New Show" feature me your host Troy Mcleur. Something blah blah blah
"""
所以,我的问题是,是否可以编写一些 Python 来解析第一组和第二组名称,以便只打印它们?因此,输出将仅为:
[+] Start group 1
derrek
bob
james
harry
[+] Start group 2
Will
Paul
Mark
Eric
目前,我目前拥有的代码是这样的:
for line in file:
if 'Start Group' in line:
print line
break
for line in file:
if 'Start Group' in line:
break
print line
但这只会打印组 1,但不会打印下一组。此外,有时某些文件可能有 2 到 9 个组,所以我需要它来循环访问并找到 Group 的所有实例,并打印其中的所有名称。
这可以工作:
from __future__ import print_function
show = False
for line in fobj:
if line.strip().startswith('[+]'):
print()
show = True
elif not line.strip():
show = False
if show:
print(line, end='')
输出:
[+] Start group 1
+derrek
+bob
+james
+harry
[+] Start group 2
+Will
+Paul
+Mark
+Eric