[英]Read text file data that is separated by 3 spacing
Hi i am trying to extract out the information on Column [3] and [4] at row 180. Problem i am facing is 嗨,我正在尝试提取第180行第[3]和[4]列上的信息。我面临的问题是
Error it give me: line = reader[180][3] IndexError: list index out of range 它给我的错误是:line = reader [180] [3] IndexError:列表索引超出范围
@@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
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; 如果我正确地理解了您的问题,则您很难拆分字段,因为它们之间用3个空格隔开。 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. \\s
是正则表达式类,表示空白(制表符,空格,新行,和退格?) +
手段应用先前的模式的一个或更多次 ,因此这个表达式将匹配的一个或多个空格字符。 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. 编辑如下所述,这仅在导入re并使用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. 请记住,python索引从0开始,我假设当您说第180行时,是指文件中的第181行以及第3和4列是文件中的第4列和第5列。 If not, -1 from those numbers. 如果不是,则从这些数字中返回-1。
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.