看起来文件可能有“其他”分隔符号,我们在小学学习的那个:
In [185]: b'\xc3\xb7'
Out[185]: b'\xc3\xb7'
In [186]: _.decode()
Out[186]: '÷'
最近的 numpy 版本可以更好地处理编码。早期的尝试完全以字节串模式(对于 Py3)工作以与 Py2 兼容。但现在它需要一个encoding 参数。
In [68]: txt = '''(10/2), 1, 2
...: (10/2), 3,4'''
In [70]: np.genfromtxt(txt.splitlines(), dtype=None, delimiter=',')
/usr/local/bin/ipython3:1: VisibleDeprecationWarning: Reading unicode strings without specifying the encoding argument is deprecated. Set the encoding, use None for the system default.
#!/usr/bin/python3
Out[70]:
array([(b'(10/2)', 1, 2), (b'(10/2)', 3, 4)],
dtype=[('f0', 'S6'), ('f1', '<i8'), ('f2', '<i8')])
In [71]: np.genfromtxt(txt.splitlines(), dtype=None, delimiter=',',encoding=None
...: )
Out[71]:
array([('(10/2)', 1, 2), ('(10/2)', 3, 4)],
dtype=[('f0', '<U6'), ('f1', '<i8'), ('f2', '<i8')])
诚然,从字符串列表中模拟加载与从文件加载不同。我没有安装早期的 numpys(而不是在 Py2 上),所以无法显示之前发生的事情。但我的直觉是“(10/2)”以前不应该出现问题,至少在 ASCII 文件中不会出现问题。字符串中没有任何特殊字符。
与另一个鸿沟:
In [192]: txt = '''(10÷2), 1, 2
...: (10÷2), 3,4'''
In [194]: np.genfromtxt(txt.splitlines(), dtype=None, delimiter=',',encoding='ut
...: f8')
Out[194]:
array([('(10÷2)', 1, 2), ('(10÷2)', 3, 4)],
dtype=[('f0', '<U6'), ('f1', '<i8'), ('f2', '<i8')])
文件中的相同内容:
In [200]: np.genfromtxt('stack49859957.txt', dtype=None, delimiter=',')
/usr/local/bin/ipython3:1: VisibleDeprecationWarning: Reading unicode strings without specifying the encoding argument is deprecated. Set the encoding, use None for the system default.
#!/usr/bin/python3
Out[200]:
array([(b'(10\xf72)', 1, 2), (b'(10\xf72)', 3, 4)],
dtype=[('f0', 'S6'), ('f1', '<i8'), ('f2', '<i8')])
In [199]: np.genfromtxt('stack49859957.txt', dtype=None, delimiter=',',encoding=
...: 'utf8')
Out[199]:
array([('(10÷2)', 1, 2), ('(10÷2)', 3, 4)],
dtype=[('f0', '<U6'), ('f1', '<i8'), ('f2', '<i8')])
在早期版本中,encoding 可以在 converter 中实现。我在之前的 SO 问题中帮助完成了这项任务。