Skip to main content
 首页 » 编程设计

python之在python中多次从文件中的一个特定单词读取到文件中的另一个特定单词

2025年05月04日16开发

好的,就这样。这有点烦人。我有一个包含多个“部分”的文件。文件可能是这样的:

""" 
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 个组,因此我需要它遍历并找到组的所有实例,并打印其中的所有名称。

请您参考如下方法:

这可行:

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