import numpy as np
path = "<insert file path here>/infotable.txt"
# read off column locations from a text editor.
# I used Notepad++ to do that.
column_locations = np.array([1, 38, 52, 61, 70, 78, 98, 111, 120, 127, 132])
# My text editor starts counting at 1, while numpy starts at 0. Fixing that:
column_locations = column_locations - 1
# Get column widths
widths = column_locations[1:] - column_locations[:-1]
data = np.genfromtxt(path, dtype=None, delimiter=widths, autostrip=True)
numpy模块有一个函数可以实现这一点(见最后一行):
根据具体的用例,您可以使用不同的方法来获得列宽,但是您得到了这个想法。
dtype=None
确保numpy为您确定数据类型;这与省略dtype
参数非常不同。最后,autostrip=True
去掉前导空格和尾随空格。在输出(
data
)是structured array。在您需要分隔符为两个或更多个空格(而不是一个或多个空格)。这里有一个解决方案:
结果:
^{2}$相关问题 更多 >
编程相关推荐