我有一个似乎无法解决的问题;道歉,如果这是重复但从来没有真正的答案。我从配置文件中提取特定信息,该文件以文本块的形式显示信息,我只需要打印特定的块,而不需要标题。因此,例如(使用下面的文本格式)我只想捕获Header2下面的信息,但不想捕获标题3之外的任何信息:
# output could containmultiple headers, and lines, or no lines per header this is an example of what could be present but it is not absolute.
header1
-------
line1
line2
line3 # can be muiplies availables or known
header2
-------
line1
line2
line3 # can be muiplies availables or known
header3
-------
header4
-------
line1
line2
line3 # can be multiple linnes or none not known
这是我开始使用的代码,但卡在第二个循环布尔或逻辑上,只打印该标题块的行:
Raw_file = "scrap.txt"
scrape = open(Raw_file,"r")
for fooline in scrape:
if "Header" in fooline:
#print(fooline) # prints all lines
#print lines under header 2 and stop before header 3
scrape.close()
答案 0 :(得分:2)
使用标题行的检测来打开/关闭控制打印的布尔值:
RAW_FILE = "scrap.txt"
DESIRED = 'header2'
with open(RAW_FILE) as scrape:
printing = False
for line in scrape:
if line.startswith(DESIRED):
printing = True
elif line.startswith('header'):
printing = False
elif line.startswith('-------'):
continue
elif printing:
print(line, end='')
<强>输出强>
> python3 test.py
line1
line2
line3 # can be muiplies availables or known
>
根据需要调整。
答案 1 :(得分:1)
您可以考虑使用正则表达式将其分解为块。
如果文件的大小可管理,请立即全部阅读并使用正则表达式:
(^header\d+[\s\S]+?(?=^header|\Z))
把它分成块。 Demo
然后你的Python代码看起来像这样(在标题之间获取任何文本):
import re
with open(fn) as f:
txt=f.read()
for m in re.finditer(r'(^header\d+[\s\S]+?(?=^header|\Z))', txt, re.M):
print(m.group(1))
如果文件大于您想要读取的文件,则可以将mmap与正则表达式一起使用,并以相当大的块读取文件。
如果您只查找单个标题,则更容易:
m=re.search(r'(^header2[\s\S]+?(?=^header|\Z))', txt, re.M)
if m:
print(m.group(1))
答案 2 :(得分:0)
您可以根据匹配的header2
和header3
内容设置启动和停止收集的标记。
example.txt
包含提供的完整示例数据:
f = "example.txt"
scrape = open(f,"r")
collect = 0
wanted = []
for fooline in scrape:
if "header2" in fooline:
collect = 1
if "header3" in fooline:
collect = 2
if collect == 1:
wanted.append(fooline)
elif collect == 2:
break
scrape.close()
wanted
输出:
['header2\n',
'-------\n',
'line1\n',
'line2\n',
'line3 # can be muiplies availables or known\n',
'\n']
答案 3 :(得分:0)
最初,将flag
设为False
。检查该行是否以header2
开头。如果True
,请设置flag
。如果该行以header3
开头,请将flag
设置为False
。
如果设置了flag
,则打印行。
Raw_file = "scrap.txt"
scrape = open(Raw_file,"r")
flag = False
for fooline in scrape:
if fooline.find("header3") == 0: flag = False # or break
if flag:
print(fooline)
if fooline.find("header2") == 0: flag = True
scrape.close()
输出:
-------
line1
line2
line3 # can be muiplies availables or known