2016-04-18 17 views
0

ユニコード要素を含むnumpy配列をテキストファイルにエクスポートしようとしています。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」から「マカ」から「C」を変更した場合、私はエラーを取得する:

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) 

はどうやってUnicode文字を書き込むためにnumpyのからsavetxtを設定することができますか?

+0

リストまたは長いテキストの場合、これらの文字列をどのように書きますか?あなたはまだ 'wb'モードでファイルを開きますか? – hpaulj

+0

'wd'モードは、 'w'だけが私にエラーを投げるためです。 – umLu

答えて

3

これを達成するにはさまざまな方法がありますが、これらの状況ではユニコード文字を使用できるようにnumpy配列を特別な方法(通常はdtypeを使用)で設定する必要があります。

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import numpy as np 

dt = np.dtype(str, 10) 
array_unicode=np.array(['maça','banana','morangou'], dtype=dt) 

with open('array_unicode.txt','wb') as f: 
    np.savetxt(f, array_unicode, fmt='%s') 

アレイの文字列の長さとdtype内で設定する長さに注意する必要があります。短すぎるとデータが切り捨てられ、長すぎると無駄になります。 Numpy data type objects (dtype) documentationを読むことをお勧めします。データフォーマットに応じて配列を設定する方法は他にもたくさんあります。

http://docs.scipy.org/doc/numpy-1.9.3/reference/arrays.dtypes.html

ここで保存する前に、Unicodeへの変換を行うことができ、代替機能です:

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import numpy as np 

array_unicode=np.array([u'maça',u'banana',u'morangou']) 

def uniArray(array_unicode): 
    items = [x.encode('utf-8') for x in array_unicode] 
    array_unicode = np.array([items]) # remove the brackets for line breaks 
    return array_unicode 

with open('array_unicode.txt','wb') as f: 
    np.savetxt(f, uniArray(array_unicode), fmt='%s') 

基本的にはあなたのnp.savetxtは当時、迅速な変換のためuniArrayを呼び出します。これよりも良い方法があるかもしれませんが、私がnumpyを使ってからしばらくしています。それは常にエンコーディングではやや面倒なようです。 python3で

+0

numpyを使用する主な理由の1つは、ループを回避することです。 numpyのメソッドや関数を使用したソリューションはありませんか? – umLu

+0

なぜあなたの弦の前に「u」を使用しているのかはっきりしていません....その理由がありますか?エンコーディングを宣言すれば、それは必要ありません。これを行う他の方法もあります。 'dtypes'とその使い方に関するドキュメントを読むべきです。 –

+1

'savetxt'はあなたの配列の各行に対して' file.write(fmt%tuple(row)) 'を実行するループを使います。また、エンコード/デコードは文字列メソッドで繰り返し実行されます。ここで配列を使うことで時間が節約されるわけではありません。 – hpaulj

3

ipthon-qt端子)私が行うことができます:PY2と3の両方では

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 

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は、文字列のメソッドなので、個別に適用する必要があります配列(またはリスト)の要素

私はencodeを使用する場合は戻るPY3側で、私が手:

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の世代があります。

それが助け場合は、ここで(wbファイルモードと一緒に)np.savetxt使用していることをnp.lib.npyio.asbytes関数のコードです:

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メソッドを適用する必要があります。

関連する問題