我正在尝试使用numpy.genfromtxt函数导入包含字符串和数字列的txt。基本上我需要一个字符串数组。这是一个示例txt给我带来麻烦:
import numpy as np
decodf= lambda x: x.decode('utf-16')
sample = np.genfromtxt(('ztest.txt'), dtype=str,
converters = {0:decodf, 1:decodf},
delimiter='\t',
usecols=0)
print(sample)
txt被编成unicode。这是我正在使用的代码:
['H2S' 'None']
这是输出:
[b'\xff\xfeH\x002\x00S' b'\x00g\x00\xe8\x00n']
我尝试了几种方法来解决这个问题。通过输入dtype = None并消除转换器,我得到:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
我也试过消除转换器并放入dtype = str并得到:
pf.addAncestorListener(new AncestorListener() {
@Override
public void ancestorRemoved(AncestorEvent event) {}
@Override
public void ancestorMoved(AncestorEvent event) {}
@Override
public void ancestorAdded(AncestorEvent event) {
event.getComponent().requestFocusInWindow();
}
});
我明白这是一个麻烦的功能。我看到了不同的选择 (例如:here)但无法让任何人工作。
我做错了什么?与此同时,我正在调查熊猫...... 提前致谢
答案 0 :(得分:1)
您的文件编码为UTF-16,前两个字符为BOM。
试试这个(使用python 2.7):
import io
import numpy as np
with io.open('ztest.txt', 'r', encoding='UTF-16') as f:
data = np.genfromtxt(f, delimiter='\t', dtype=None, usecols=[0]) # or dtype=str
使用Unicode文件在python 3中运行时, genfromtxt
会出现一些问题。作为解决方法,您可以在将行传递到genfromtxt
之前对行进行简单编码。例如,以下行在将行传递给genfromtxt
之前将每行编码为latin-1:
import io
import numpy as np
with io.open('ztest.txt', 'r', encoding='UTF-16') as f:
lines = [line.encode('latin-1') for line in f]
data = np.genfromtxt(lines, delimiter='\t', dtype=None, usecols=[0])