【问题标题】:python 2.5 encodingpython 2.5 编码
【发布时间】:2012-08-23 07:43:51
【问题描述】:
# -*- coding: utf-8 -*-
from pyquery import PyQuery as pq
from urllib import urlencode
from urllib2 import Request,urlopen
    def sendRequest(url, data = None, headersOnly = False):
    headers  = { 'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; en-US;)' }
    request  = Request(url, data, headers)
    return urlopen(request).read()

resp = sendRequest("https://foursquare.com/v/rivers-edge-cafe--    morrison/4c1907776e02b7132eae627b")
print pq(resp)("#venueCategories").text()

输出应该是 Café、Burger Joint、Sandwich Place 但有异常:

Traceback (most recent call last):
  File "unicodeerr1.py", line 11, in <module>
    print pq(resp)("#venueCategories").text()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128)

【问题讨论】:

  • 这可能是您终端的本地问题。

标签: python encoding utf-8 character-encoding


【解决方案1】:

您需要为您的源代码指定编码,或使用转义字符。

# -*- coding: utf-8 -*-

print 'caf\xc3\xa9' # UTF-8 representation of e accent egu.

您可能希望使用 Unicode 文字(此处使用 Unicode 转义字符):

print u'caf\u00e9'

请阅读Unicode HOWTO 以充分了解这里发生的情况。其他有用的文档:

请注意,您的具体错误与 python 2.5 与 2.7 没有任何关系,而是与您正在打印的任何内容的输出编码有关。。在您使用 python2.5 的服务器上,没有指定编码或者它被显式设置为 ASCII,但在您使用 python 2.7 的本地计算机上,您很可能正在处理支持 UTF-8 的终端。

【讨论】:

    【解决方案2】:

    我刚刚升级到 python 2.7,我的所有编码问题都已修复。

    【讨论】:

      猜你喜欢
      • 2010-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多