Python: UnicodeEncodeError: 'latin-1' 编解码器无法对位置的字符进行编码

标签 python unicode

我收到这个错误:

File "run.py", line 37, in <module>
 print str1
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 24-29: ordinal not in range(256)

尝试简单地打印一些日语文本时。实际上,字符串看起来像这样:

\u5149\u66dc\u65e5\u3067\u30e9\u30c6 \u30d4\u30af\u30b7\u30fc\u4e71\u7372\u884c\u304d\u307e\u3059 \u5e0c\u671b\u8005\u52df\u96c6\u4e2d\u3067\u3059\uff3e\uff3e

来自 JSON 文件。我怎样才能打印这个?

代码:

url = "http://www.blah.com/json"
try:
  result = simplejson.load(urllib2.urlopen(url))
except IOError:
  print "Cannot open URL"
  data = "error"

for msg in result["msg"]:
  str1 = msg["character"] + " : " + msg["message"]
  print str1

repr(str1) 是

u'Anys : \u5149\u66dc\u65e5\u3067\u30e9\u30c6 \u30d4\u30af\u30b7\u30fc\u4e71\u7372\u884c\u304d\u307e\u3059 \u5e0c\u671b\u8005\u52df\u96c6\u4e2d\u3067\u3059\uff3e\uff3e'

打印(sys.stdout.encoding)是

ISO-8859-1

最佳答案

您看到的错误是因为您的终端使用 latin-1 作为编码,作为旁注,您可以通过在 shell 中执行以下操作来检查终端的编码(假设它是您的标准输出):

$ python -c "import sys; print sys.stdout.encoding"

现在要以 UTF-8 打印,您应该像这样手动将字符串编码为 utf-8:

s = u"\u5149\u66dc\u65e5\u3067\u30e9\u30c6 \u30d4\u30af\u30b7\u30fc\u4e71\u7372\u884c\u304d\u307e\u3059 \u5e0c\u671b\u8005\u52df\u96c6\u4e2d\u3067\u3059\uff3e\uff3e"
print s.encode('utf-8')
#Output: 光曜日でラテ ピクシー乱獲行きます 希望者募集中です^^

关于Python: UnicodeEncodeError: 'latin-1' 编解码器无法对位置的字符进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7286968/

相关文章:

url - Unicode 字符是否有已知的 URI 方案或 URN 命名空间?

php - 如何获取 utf-8 字符串中给定字符的代码点编号?

python - 为 Pandas 中每次出现的字符串创建一个新列

python - Pandas DataFrame 的 str 计数中的奇怪行为

python - 如何使用 python 列表列表?

python - 运行存储过程时分区键错误

python - 将希腊语句子括在标签之间或查找并替换包含希腊语字符的句子部分

python - 我究竟做错了什么?随机数猜谜游戏

python - 如何在Python中使用Textract库加载unicode字符串?

regex - 取消转义字符串中的 unicode