代码之家  ›  专栏  ›  技术社区  ›  Dan Lew

Python 2 vs. Python 3 - urllib formats

  •  21
  • Dan Lew  · 技术社区  · 15 年前

    import urllib, json
    response = urllib.urlopen("http://reddit.com/.json")
    content = response.read()
    data = json.loads(content)
    

    思想 the equivalent code in Python 3 would be this:

    import urllib.request, json
    response = urllib.request.urlopen("http://reddit.com/.json")
    content = response.read()
    data = json.loads(content)
    

    import urllib.request, json
    response = urllib.request.urlopen("http://reddit.com/.json")
    content = response.read()
    data = json.loads(content.decode("utf8"))
    

    我做错什么了?

    编辑:问题是我无法使数据进入可用状态;即使JSON加载了数据,但其中的一部分是不可显示的,我希望能够将数据打印到屏幕上。

    第二次编辑:看起来,问题更多地与打印有关,而不是与解析有关。亚历克斯的回答为脚本在Python3中工作提供了一种方法,将IO设置为utf8。但问题仍然存在:为什么代码在python 2中工作,而不是python 3?

    3 回复  |  直到 8 年前
        1
  •  15
  •   Alex Martelli    15 年前

    f.read() fails because there's no f barename defined).

    在PY3中, ur = response.decode('utf8') works perfectly well for me, as does the following json.loads(ur) . 也许错误的复制品和粘贴会影响你的2-3次转换尝试。

        2
  •  7
  •   Jose Luis Garcia    9 年前

    Depends of your python version you have to choose the correct library.

    对于Python 3.5

    import urllib.request
    data = urllib.request.urlopen(url).read().decode('utf8')
    

    对于Python 2.7

    import urllib
    url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address})   
    uh = urllib.urlopen(url)
    
        3
  •  0
  •   Community CDub    8 年前

    请看 that answer in another Unicode related question.

    Now: the Python 3 str (Python 2) unicode )类型是一个理想化的对象,从它处理_字符_,而不是_字节__的意义上来说。为了用于/来自磁盘/网络数据,这些字符需要通过转换表,A.K.A编码A.K.A代码页编码为字节/从字节解码。由于操作系统的多样性,python在历史上一直避免猜测编码应该是什么;这一点多年来一直在改变,但仍然坚持“在面对歧义时,拒绝猜测的诱惑”的原则。

    谢天谢地,Web服务器使您的工作更容易。你的 response 以上应该给你所有需要的额外信息:

    >>> response.headers['content-type']
    'application/json; charset=UTF-8'
    

    因此,每次向Web服务器发出请求时,都要检查content-type头中的charset值,并将请求的数据解码为unicode(python 3: bytes.decode(charset) 艾斯 STR )通过使用字符集。