我正在尝试在 python 中打开一个文本文件作为数组或列表列表。该文件如下所示。
另外,这里是文本文件的链接。
ftp://rammftp.cira.colostate.edu/demaria/ebtrk/ebtrk_atlc.txt
AL0188 ALBERTO 080518 1988 32.0 77.5 20 1015 -99 -99 -99 -99 0 0 0 0 0 0 0 0 0 0 0 0 * 218.
AL0188 ALBERTO 080600 1988 32.8 76.2 20 1014 -99 -99 -99 -99 0 0 0 0 0 0 0 0 0 0 0 0 * 213.
AL0188 ALBERTO 080712 1988 41.5 69.0 35 1002 -99 -99 1012 60 100100 50 50 0 0 0 0 0 0 0 0 * 118.
AL0188 ALBERTO 080718 1988 43.0 67.5 35 1002 -99 -99 1008 50 100100 50 50 0 0 0 0 0 0 0 0 * 144.
AL0188 ALBERTO 080800 1988 45.0 65.5 35 1004 -99 -99 1008 50 -99-99-99-99 0 0 0 0 0 0 0 0 * 22.
AL0188 ALBERTO 080806 1988 47.0 63.0 35 1006 -99 -99 1008 50 -99-99-99-99 0 0 0 0 0 0 0 0 * 64.
我尝试使用 NumPy genfromtxt 但返回错误,因为它无法判断 100100 是两列中的两个元素。它将其视为一列中的一个条目,因此返回错误,指出每行中的列数不匹配。
有办法解决这个问题吗?谢谢
最佳答案
您可以提供分隔符大小作为参数。示例:
import numpy as np
import sys
with open('ebtrk_atlc.txt', 'rU') as f:
data = np.genfromtxt(f,
dtype=None,
delimiter=[7, 10, 7, 4, 5, 6, 4, 5, 4, 4, 5, 4, 4, 3, 3, 3])
print data
将作为输出给出(省略前几行)
('AL0188 ', 'ALBERTO ', 80712, 1988, 41.5, 69.0, 35, 1002, -99, -99, 1012, 60, 100, 100, 50, 50)
('AL0188 ', 'ALBERTO ', 80718, 1988, 43.0, 67.5, 35, 1002, -99, -99, 1008, 50, 100, 100, 50, 50)
('AL0188 ', 'ALBERTO ', 80800, 1988, 45.0, 65.5, 35, 1004, -99, -99, 1008, 50, -99, -99, -99, -99)
如您所见,100100
字段已分开。当然,您必须提供正确的字段类型和维度,此示例仅说明这是可能的。例如,将代码更改为
import numpy as np
import re
import sys
with open('ebtrk_atlc.txt', 'rU') as f:
dt = "a7,a10,a7,i4,f5,f6,i4,i5,i4,i4,i5,i4,i4,i3,i3,i3"
data = np.genfromtxt(f,
dtype=dt,
delimiter=map(int, re.split(",?[a-z]", dt[1:])),
autostrip=True)
将结果更改为
('AL0188', 'ALBERTO', '080712', 1988, 41.5, 69.0, 35, 1002, -99, -99, 1012, 60, 100, 100, 50, 50)
('AL0188', 'ALBERTO', '080718', 1988, 43.0, 67.5, 35, 1002, -99, -99, 1008, 50, 100, 100, 50, 50)
('AL0188', 'ALBERTO', '080800', 1988, 45.0, 65.5, 35, 1004, -99, -99, 1008, 50, -99, -99, -99, -99)
去除字符串周围的空白并显式地将某些类型设置为 float 。可以找到更多文档 here ,检查底部的示例。
关于python - 在python中打开文本文件作为数组或列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21405829/