我在从文本文件中提取行时遇到很大问题: 我的文本文件构建如下:
BO_ 560 VR_Sgn_1: ALMN
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
BO _ 561 VSet_Current : ACM
SG_2_ Vr_set
SG_3 Dars
BO_ 4321 CDSet_tr : APL
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
SG_1_ Vr_1
SG_2_ Vr_set
SG_3 Dars
...
文本文件包含大约1000个“BO_”块......
我想在“BO_”之间加上表达式。 这是我以前的代码:
show_line= False
with open("test.txt") as f:
for line in f:
if line.startswith("BO_ 560"):
show_line=True
elif line.startswith("\n")
show_line= False
if show_line and not line.startswith("BO_ 560")
print line
在这种情况下,我希望得到以下输出:
SG_1_ Vr
SG_2_ Vr_set
SG_3 Dars
任何人都可以帮助我吗?
答案 0 :(得分:1)
我觉得有问题:
elif line.startswith("\n")
你想等待下一个“BO_”而不是EOL来禁用show_line,试试这个:
show_line = False
with open("test.txt") as f:
for line in f:
if line.startswith("BO_ 560"):
show_line = True
elif line.startswith("BO_"):
show_line = False
elif show_line:
print line
答案 1 :(得分:0)
当您看到BO_ or BO _
我不确定你是否只想要第一块或全部。
以下选项是否解决了您的问题。
show_line = False
with open("test.txt") as f:
for line in f:
line = line.strip("\n")
if line.startswith("BO_ ") or line.startswith("BO _ "):
show_line = False if show_line else True
continue
if show_line:
print line
答案 2 :(得分:0)
如果您想要输出“BO”之间的所有块,您可以执行以下操作:
with open("test.txt") as f:
for line in f:
if line.startswith("BO"):
print ""
else:
print line