【发布时间】:2013-07-30 17:49:56
【问题描述】:
我想将一个(非常大的、空格分隔的、两列的)文本文件中的数据读入 Python 字典。我尝试使用 for 循环来做到这一点,但这太慢了。更快的是使用 numpy loadtxt 将其读取到结构数组中,然后将其转换为字典:
data = np.loadtxt('filename.txt', dtype=[('field1', 'a20'), ('field2', int)], ndmin=1)
result = dict(data)
但这肯定不是最好的方法吗?有什么建议吗?
我需要其他东西的主要原因是以下不起作用:
data[0]['field1'].split(sep='-')
导致报错信息:
TypeError: Type str doesn't support the buffer API
如果 split() 方法存在,为什么我不能使用它?我应该使用不同的 dtype 吗?还是有不同的(快速)方式来读取文本文件?我还有什么遗漏的吗?
版本: 蟒蛇版本 3.3.2 numpy 版本 1.7.1
编辑:
将data['field1'].split(sep='-') 更改为data[0]['field1'].split(sep='-')
【问题讨论】:
-
这些天我将不得不尝试理解 unicode... 顺便说一句,正确的做法是将答案写为正确的答案并接受它,而不是包含它在你的问题中。
-
好的,完成()。再次感谢。
标签: python dictionary numpy split