3

titleテキスト フィールドとを含むクラス チャンクがありますtext。それらを印刷したいとき、私は (驚き、驚き!) を得UnicodeDecodeErrorます。出力文字列をフォーマットしようとするとエラーが発生しますが、テキストとタイトルを連結して返すと、エラーは発生しません。

class Chunk:
  # init, fields, ...

  # this implementation will give me an error
  def __str__( self ):
    return u'{0} {1}'.format ( enc(self.text), enc(self.title) )

  # but this is OK - all is printed without error
  def __str__( self ):
    return enc(self.text) + enc(self.title)

def enc(x):
  return x.encode('utf-8','ignore') # tried many combinations of arguments...


c = Chunk()
c.text, c.title = ... # feed from external file
print c

バム!エラー!

return u'{0} {1}'.format ( enc(self.text), enc(self.title) )
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 2844: ordinal not in range(128)

encode/ decode/ utf-8/ ascii/ replace/ ignore/...のすべての可能な組み合わせを使用したと思います。

(Python の Unicode の問題は本当にイライラします!)

4

2 に答える 2

4
  1. Unicodeを返すときは、ではなくオーバーライド__unicode____str__する必要があります。
  2. .encode()入力はすでにユニコードであるため、を呼び出す必要はありません。書くだけ

    def __unicode__(self):
        return u"{0} {1}".format(self.text, self.title)
    
于 2012-11-06T07:28:07.710 に答える
3

2.x Python の Unicode 問題を回避する最も簡単な方法は、全体的なエンコーディングを utf-8 に設定することです。そうしないと、そのような問題が突然の場所で常に発生します。

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
于 2012-11-06T07:33:14.297 に答える