문제

Hi i am trying to extract out the information on Column [3] and [4] at row 180. Problem i am facing is

  1. Element is separated by 3 spaces
  2. The @@Data starts at row 180
  3. The code I am using can't extract out the specific Column
  4. Error it give me: line = reader[180][3] IndexError: list index out of range

    @@Data: Source 0 in text format:        
    1    2    2    1    1    9    1    1    -2    2    1    -3    3    1 
    3    2    2    1    1    9    1    1    -2    2    1    -3    3    1 
    4    2    2    1    1    9    1    1    -1    1    1    -2    2    1 
    

Code i am using

     reader = list(csv.reader(f, delimiter=' '))
     SatIP, CoerIP = getSatHcoer(reader)
     print SatIP, CoerIP

     def getSatHcoer(reader): 
     line = reader[180][3]
     Sat = line.split('    ')
     Sat =  Sat[len(Sat)-1]
     line = reader[180][4]
     Coer = line.split('     ')
     Coer =  Coer[len(Coer)-1] 
     return Sat, Coer
     pass
도움이 되었습니까?

해결책

If I understand your question correctly, you are having trouble splitting the fields because they are separated by 3 spaces; you can actually split on regular expressions, try using:

 Coer = line.split("\s+")

\s is the regular expression class that represents whitespace (tabs, spaces, newlines, and backspaces?) + means apply the previous pattern one or more times, so this expression will match one or more space characters. Using this method, it shouldn't matter how many spaces separate fields.

EDIT As mentioned below this only works if you import re and use re.split.

 import re
 Coer = re.split("\s+",line)

다른 팁

Keeping in mind that python indexing starts from 0, I'm assuming that when you say line 180, you mean the 181st line in the file and column 3 & 4 are the 4th and 5th columns in the file. If not, -1 from those numbers.

def getSatHcoer(reader):
    Sat = reader[180][3]
    Coer = reader[180][4]
    return Sat, Coer

with open('file.txt', 'r') as f:
    reader = [[x.strip().split('   ')] for x in f]
SatIP, CoerIP = getSatHcoer(reader)
print SatIP, CoerIP
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top