将文本文件转换为列向量

时间:2015-06-20 02:29:31

标签: python text

我有一个文本文件,我想分成列向量:

dtstamp ozone   ozone_8hr_avg   

06/18/2015 14:00:00 0.071   0.059   

06/18/2015 13:00:00 0.071   0.053   

如何以下列格式生成输出?

dtstamp = [06/18/2015 14:00:00, 06/18/2015]

ozone = [0.071, 0.071]

etc.

4 个答案:

答案 0 :(得分:1)

import datetime

dtstamp = [] # initialize the dtstamp list
ozone = [] # initialize the ozone list

with open('file.txt', 'r') as f:
    next(f) # skip the title line
    for line in f: # iterate through the file
        if not line: continue # skip blank lines
        day, time, value, _ = line.split() # split up the line
        dtstamp.append(datetime.datetime.strptime(' '.join((date, time)),
          '%m/%d/%Y %H:%M:%S') # add a date
        ozone.append(float(value)) # add a value

然后,您可以将这些listzip合并,以使用相应的日期/值:

for date, value in zip(dtstamp, ozone):
    print(date, value) # just an example

答案 1 :(得分:1)

其他答案很少似乎在运行它们时出错。

试试这个,它应该像魅力一样!

dtstmp = []
ozone = []
ozone_8hr_avg = []
with open('file.txt', 'r') as file:
  next(file)
  for line in file:
    if (line=="\n")  or (not line):     #If a blank line occurs
      continue
    words = line.split()                #Extract the words
    dtstmp.append(' '.join(words[0::1]))#join the date
    ozone.append(words[2])              #Add ozone
    ozone_8hr_avg.append(words[3])  #Add the third entry

print "dtstmp =", dtstmp
print "ozone =", ozone
print "ozone_8hr_avg =", ozone_8hr_avg

答案 2 :(得分:0)

我会查看pandas http://pandas.pydata.org或csv模块。使用cvs,你必须自己制作列,因为它会为你提供行。

rows = [row for row in csv.reader(file,  delimiter='\t') ] #get the rows
col0 = [ row[0] for row in rows ] # construct a colonm from element 0 of each row.

答案 3 :(得分:0)

试试我的朋友:

# -*- coding: utf8 -*-
file = open("./file.txt")

lines = file.readlines()

data = []
data_hour = []
ozone = []
ozone_8hr_avg = []

for i_line in lines:
    data.append(i_line.split()[0:2])
    data_hour.append(' '.join(data[-1]))
    ozone.append(i_line.split()[2])
    ozone_8hr_avg.append(i_line.split()[3])

#print (data)
print (data_hour)
print (ozone)
print (ozone_8hr_avg)

如果这有助于你记住接受答案。