2014-07-11 64 views
1

我想打印的文本文件的選定部分,text.txt,其中包含:Python的解析選定的區域/文本文件的範圍

tickme 1.1(no.3) 
lesson1-bases 
lesson2-advancedfurther 
para:using the dsp signals are sened via a transmitter to conver to analong signals and gets the output in the form of digital signal 

tickme 2.2(no.4) 
lesson1-basics2 
lesson2-advanced4 
para:using the DIGITAL signals are sened via a transmitter to conver to analong signals and gets the output in the form of digital signal 

tickme 3.3(no.5) 
lesson1-bas 
lesson2-adv 
para:using the dsp signals are sened via a transmitter to conver to analong signals and gets the output in the form of digital signal 

這包括3蜱我,但我想選擇一個特定的tickme 2.2(no.4)在tickme 3.3(no.5)開始之前,我必須解析文本。

因此,如果段落中有「DIGITAL」,則必須打印「lesson1」,因爲它會導致模糊不清,因此我想選擇文本文件的範圍。

輸出:

lesson1-basics2 

因爲它有第1課通用於所有蜱我,我需要選擇特定區域tickme2.2之間解析(第4號),以tickme 3.3(第5號)有沒有辦法獲得特定區域的範圍和解析?並且可能會有大量數據在我之間打勾,與示例不同。

問題:它沒有選擇特定的範圍。

searchstring = "" 
with open('text.txt','r') as file: 

    for line in file: 
     if 'tickme' in line: 
      searchstring = line 
     if searchstring != '': 
      if 'DIGITAL' in line: 
       print(searchstring) 
       print(line) 

回答

1

分割文件放入批像這樣:

張開( 'txt.txt')爲f: 批次= []

t = [] 
for l in line: 
    if 'tickme' in l: 
     # Start a new bactch after saving the previous batch 
     if t: batches.apend(t) 
     t = [l.strip()] 
    else: 
     if len(l.strip()) > 1: t.append(l.strip())