0

cafe単語を含む文字列(ただし、アクセント付きの) を JavaScript ソース ファイルから Python スクリプトにコピーしeています。そこでは、データに対して何らかの処理を行い、JSON を出力する必要があります。ただし、エンコード/デコードの詳細に頭を悩ませています。これは、おそらく次の例で最もよく説明されています。

$ python
>>> import urllib2, json
>>> the_name = "Tasty Caf%C3%E9"
>>> the_name
'Tasty Caf%C3%E9'
>>> the_name_unquoted = urllib2.unquote(the_name)
>>> the_name_unquoted
'Tasty Caf\xc3\xe9'
>>> json.dumps({'bla': the_name_unquoted})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 9: invalid continuation byte

エンコーディングがどのように機能するかを理解しようと時間を費やしましたが、明らかに理解できていません。正確にどのエンコーディング/フォーマット(ここに他の適切な用語がありますか?)がthe_name_unquoted上記にあり、utf8が正しくデコードできないのは何ですか?

4

1 に答える 1

1

その文字は Unicode エンコーディングでサポートされているためです。これは、文字列を Unicode に変換することで修正できます。

the_name = u'Tasty Caf%C3%E9'

または、文字列が既に存在する場合は、それを変換できます。

the_name = 'Tasty Caf%C3%E9'
the_name = unicode(the_name) 
# or..
the_name = the_name.decode('utf8', the_name)
于 2012-12-20T09:39:04.943 に答える