2012-02-09 14 views
0

我想知道如何搜索單詞POLYLINE的文本文檔,然後一旦找到它,如何繼續搜索文本文檔以獲取POLYLINE的更多屬性,如x座標和y座標,然後找到下一個POLYLINE然後再做一次。匹配一行後,如何讀取更多行和記錄值,然後重新開始? Python

我有一個文本文件,它看起來像這樣:

  1. 折線
  2. 等等
  3. X座標
  4. Ÿ座標
  5. 等等
  6. blah
  7. X座標
  8. Ÿ座標
  9. 折線
  10. 等等...

我所有的代碼不迄今發現的字折線,我我試圖收集POLYLINE的屬性。 這裏是我到目前爲止的代碼:

import re 

fileName = open("textdoc.txt, "r") 



for line in fileName: 
    if re.match("POLYLINE", line): 
     print line 



fileName.close() 

我怎樣才能解決這個問題?

回答

0
for line in fileName: 
    if re.match("POLYLINE", line): 
     for line in filename: 
      if re.match(xcoord,line): 
       dostuff() 
      if re.match(ycoord,line): 
       dostuff() 

至於怎樣才能真正找到座標,我們很難用你提供的東西做任何事情。如果沒有圖案顯示座標將顯示在哪一行,或者如果有其他數字不是您的座標,並且這些數字沒有這種類型的標識,那麼您可以做的事情就不多了。基本上,找到可以讓你將座標與其他任何東西區分開來的東西,然後搜索它。

0

假設結構是一致的,你可以收集如下的屬性。

#store polylines in a list for future use 
polylines=[] 

dataFile = open('textdoc.txt') 

#collect the attributes in dictionaries 
attrs={} 

#because it appears you need to look one line ahead to get the coordinates 
# it would be easiest to read all lines into a list 

datalines = dataFile.readlines() 
for idx, line in enumerate(datalines): 
    #handle polyline flags by storing the previous attributes 
    if 'POLYLINE' in line: 
     #attrs will evaluate to True if its not empty 
     if attrs: 
      #append the old polyline attributes and start a new one 
      polylines.append(attrs) 
      attrs = {} 

     continue 

    #collect the attributes from the line following the coord flag 
    # of course this breaks real fast if the file structure changes 
    if 'xcoord' in line: 
     #grab the coordinate from the following line 
     attrs['xcoord'] = datalines[idx + 1].strip() 
     continue 

    if 'ycoord' in line: 
     attrs['ycoord'] = datalines[idx + 1].strip() 
     continue 
相關問題