我正在尝试将包含 unicode 元素的 numpy 数组导出到文本文件。
到目前为止,我得到了以下的工作,但没有任何 unicode 字符:
import numpy as np
array_unicode=np.array([u'maca' u'banana',u'morango'])
with open('array_unicode.txt','wb') as f:
np.savetxt(f,array_unicode,fmt='%s')
如果我将“c”从“maca”更改为“ç”,我会收到错误消息:
import numpy as np
array_unicode=np.array([u'maça' u'banana',u'morango'])
with open('array_unicode.txt','wb') as f:
np.savetxt(f,array_unicode,fmt='%s')
回溯:
Traceback (most recent call last):
File "<ipython-input-48-24ff7992bd4c>", line 8, in <module>
np.savetxt(f,array_unicode,fmt='%s')
File "C:\Anaconda2\lib\site-packages\numpy\lib\npyio.py", line 1158, in savetxt
fh.write(asbytes(format % tuple(row) + newline))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 2: ordinal not in range(128)
如何从numpy设置savetxt来写入unicode字符?
请您参考如下方法:
在 Python3(ipthon-qt 终端)我可以做:
In [12]: b=[u'maça', u'banana',u'morango']
In [13]: np.savetxt('test.txt',b,fmt='%s')
In [14]: cat test.txt
ma�a
banana
morango
In [15]: with open('test1.txt','w') as f:
...: for l in b:
...: f.write('%s\n'%l)
...:
In [16]: cat test1.txt
maça
banana
morango
Py2 和 3 中的
savetxt 坚持以“wb”字节模式保存。您的错误行具有 asbytes 函数。
在我的示例中,b 是一个列表,但这并不重要。
In [17]: c=np.array(['maça', 'banana','morango'])
In [18]: c
Out[18]:
array(['maça', 'banana', 'morango'],
dtype='<U7')
写的一样。在 py3 中,默认的字符串类型是 unicode,因此不需要 u 标签——但没问题。
在 Python2 中,我通过简单的写入得到了你的错误
>>> b=[u'maça' u'banana',u'morango']
>>> with open('test.txt','w') as f:
... for l in b:
... f.write('%s\n'%l)
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 2: ordinal not in range(128)
添加 encode 会得到一个不错的输出:
>>> b=[u'maça', u'banana',u'morango']
>>> with open('test.txt','w') as f:
... for l in b:
... f.write('%s\n'%l.encode('utf-8'))
0729:~/mypy$ cat test.txt
maça
banana
morango
encode 是一种字符串方法,因此必须应用于数组(或列表)的各个元素。
回到 py3 端,如果我使用 encode 我得到:
In [26]: c1=np.array([l.encode('utf-8') for l in b])
In [27]: c1
Out[27]:
array([b'ma\xc3\xa7a', b'banana', b'morango'],
dtype='|S7')
In [28]: np.savetxt('test.txt',c1,fmt='%s')
In [29]: cat test.txt
b'ma\xc3\xa7a'
b'banana'
b'morango'
但是如果格式正确,普通的写法就可以了:
In [33]: with open('test1.txt','wb') as f:
...: for l in c1:
...: f.write(b'%s\n'%l)
...:
In [34]: cat test1.txt
maça
banana
morango
这就是混合 unicode 和 2 代 Python 的乐趣。
如果有帮助,这里是 np.savetxt 使用的 np.lib.npyio.asbytes 函数的代码(连同 wb 文件模式):
def asbytes(s): # py3?
if isinstance(s, bytes):
return s
return str(s).encode('latin1')
(注意编码固定为“latin1”)。
np.char 库将各种字符串方法应用于 numpy 数组的元素,因此 np.array([x.encode...]) 可以表示为:
In [50]: np.char.encode(b,'utf-8')
Out[50]:
array([b'ma\xc3\xa7a', b'banana', b'morango'],
dtype='|S7')
这可能很方便,尽管过去的测试表明它不能节省时间。它仍然必须将 Python 方法应用于每个元素。
