2016-07-26 43 views
0

我在提取线条勾勒出一个文本文件中的一个大问题: 我的文本文件,内置IST类似如下:提取特定的线条勾勒出的文件(蟒蛇)的

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 

....

该文本文件包括这些“BO_”块中的大约1000个...

我希望在“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 

谁能帮助我?

+1

我不确定我是否理解,你想要所有不以BO开头的行?或者你想提供一个并获得BO_ 之后的所有行,直到下一个BO_? 您现在正在接收的输出是什么? –

+2

你的代码是否工作?如果它不起作用,它会做错什么? – khelwood

+0

我得到了以“BO_#NUMBER”开头的框架。在以上我提供的算法的字符串 “BO_ 560” 和前一个例子期待以下的输出: 'SG_1_ VR SG_2_ Vr_set SG_3 Dars' 我的算法送花儿给人给了我这样的: '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' ....但那太多了。我只想拥有“BO_” –

回答

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

不客气,我很高兴它的工作...... – petrs

+0

你知道我可以用你给我的代码来区分“BO_48”和“BO_480”吗? –

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 
0

如果你想要的是输出所有与“BO的”块,你可以做这样的事情:

with open("test.txt") as f: 
    for line in f: 
     if line.startswith("BO"): 
      print "" 
     else: 
      print line 
+0

之间的表达式,我想给算法一个字符串...例如:“BO_ 560”。该算法应该给我的句子之后,开始与“SG_”....但只有表达式,直到下一个“BO_”... –