Python CSV解析和格式化

2024-05-15 06:30:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个没有太多编程知识的新手。我已经尝试完成这个任务至少8小时了。我的目标是从CSV获取最新的WMTP值:http://www.ndbc.noaa.gov/data/realtime2/MTKN6.txt-一个小示例是:

#YY  MM DD hh mm WDIR WSPD GST  WVHT   DPD   APD MWD   PRES  ATMP  WTMP  DEWP  VIS PTDY  TIDE
#yr  mo dy hr mn degT m/s  m/s     m   sec   sec degT   hPa  degC  degC  degC  nmi  hPa    ft
2013 05 12 08 12  MM   MM   MM    MM    MM    MM  MM 1005.1  12.5  11.2    MM   MM   MM    MM
2013 05 12 08 06  MM   MM   MM    MM    MM    MM  MM 1005.3  12.3  11.2    MM   MM   MM    MM
2013 05 12 08 00  MM   MM   MM    MM    MM    MM  MM 1005.0  12.2  11.2    MM   MM -1.3    MM
2013 05 12 07 54  MM   MM   MM    MM    MM    MM  MM 1005.0  12.3  11.2    MM   MM   MM    MM
2013 05 12 07 48  MM   MM   MM    MM    MM    MM  MM 1005.1  12.1  11.2    MM   MM   MM    MM
2013 05 12 07 42  MM   MM   MM    MM    MM    MM  MM 1004.8  12.0  11.2    MM   MM   MM    MM
2013 05 12 07 36  MM   MM   MM    MM    MM    MM  MM 1004.6  12.1  11.2    MM   MM   MM    MM
2013 05 12 07 30  MM   MM   MM    MM    MM    MM  MM 1004.5  12.1  11.2    MM   MM   MM    MM
2013 05 12 07 24  MM   MM   MM    MM    MM    MM  MM 1004.6  12.0  11.2    MM   MM   MM    MM

文件大约每小时更新一次,最新的条目将放在最上面。这是一个Raspberry Pi项目,因此内存和CPU资源是有限的。在

我可以访问CSV,虽然我认为我有问题,因为格式。我认为我的代码没有正确定义列。我可以打印行并在其中进行选择,但无法打印指定的行和列。在

在下面的代码中,我使用了最后两个print语句来尝试读取所需的值,该值应该接近第3行第15列,这取决于我如何读取最新的WTMP值的txt文件。在

^{pr2}$

如果有人能给我指出一个好的python初学者指南,而不是python.org网站非常感谢。在


Tags: 文件csv代码txt目标编程secmm
3条回答

源文件不是CSV;我下载的文件中没有制表符(只有空格)。这看起来有固定宽度的字段,其中有空格以确保每一行的每个字段都在同一列中。在

我建议你看看How to efficiently parse fixed width files?。在

我能够回顾所提供的答案,并通过一些工作来找出答案。在

关键的变化是以下两行:

    datareader = csv.reader((webpage), delimiter=' ',skipinitialspace=True) 

文件的格式是,列之间只使用空格而不是制表符分隔,所以跳过空格和后面的空格,直到下一列

^{pr2}$

最终代码:

import csv
import urlib
url="http://www.ndbc.noaa.gov/data/realtime2/MTKN6.txt"
webpage = urlib.urlopen(url)
datareader = csv.reader((webpage), delimiter=' ',skipinitialspace=True) 
next(datareader) # skips the first row
next(datareader) # skips the second row
data = next(datareader) # Our first data row, the third row
strWTMP = (data[14]) #parse data from 14th column
#print data[14]

##### optional additional code to convert string to float 
WTMP = float(strWTMP)  #convert value from string to float

csv模块将在每次迭代中将每一行作为一个列表读取。由于您只关心第一个数据行,请尝试以下版本:

datareader = csv.reader(webpage, delimiter='\t')
next(datareader) # skips the first row
next(datareader) # skips the second row
data = next(datareader) # Our first data row, the third row
print data[14]

请尝试使用^{}获取该语言的基本介绍。在

相关问题 更多 >

    热门问题