如何在python上使用split()字节数\类型?(从文件中读取词典)

2024-04-26 21:39:33 发布

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

我想从一个(非常大的,空格分隔的,两列)文本文件中读取数据到Python字典中。我试着用for循环来做这个,但是太慢了。更快的方法是使用numpy loadtxt将其读入struct数组,然后将其转换为字典:

data = np.loadtxt('filename.txt', dtype=[('field1', 'a20'), ('field2', int)], ndmin=1)
result = dict(data)

但这肯定不是最好的办法?有什么建议吗?在

我需要其他东西的主要原因是以下内容不起作用:

^{pr2}$

它会导致错误消息:

TypeError: Type str doesn't support the buffer API

如果split()方法存在,为什么我不能使用它?我应该使用其他数据类型吗?或者有没有不同的(快速)方式来读取文本文件?我还缺什么吗?在

版本: python 3.3.2版 numpy 1.7.1版

编辑:data['field1'].split(sep='-')更改为data[0]['field1'].split(sep='-')


Tags: 方法numpyfordata字典np数组读取数据
2条回答

标准库split根据在字符串中找到分隔符的次数返回可变数量的参数,因此不太适合数组操作。顺便说一下,我的char numpy数组(我运行的是1.7)没有split方法。在

您确实有np.core.defchararray.partition,它与all the other string operations相似,但对矢量化没有任何问题:

>>> a = np.array(['a - b', 'c - d', 'e - f'], dtype=np.string_)
>>> a
array(['a - b', 'c - d', 'e - f'], 
      dtype='|S5')
>>> np.core.defchararray.partition(a, '-')
array([['a ', '-', ' b'],
       ['c ', '-', ' d'],
       ['e ', '-', ' f']], 
      dtype='|S2')

因为: type(data[0]['field1']) 给予 <class 'numpy.bytes_'> ,当split()方法有一个“normal”字符串作为参数时,它不工作(这是一个bug吗?)在

我解决问题的方法: data[0]['field1'].split(sep=b'-') (关键是把b放在“-”前面)

当然,詹姆的建议是使用以下方法非常有帮助: np.core.defchararray.partition(a, '-') 但在这种情况下,还需要b'-'来使其工作。在

事实上,这里回答了一个相关的问题:Type str doesn't support the buffer API尽管乍一看我并不知道这是同一个问题。在

相关问题 更多 >