为什么 Python 不能正确显示此文本?(UTF-8 解码问题)

use*_*035 4 html python utf-8 python-3.x

import urllib.request as u

zipcode = str(47401)
url = 'http://watchdog.net/us/?zip=' + zipcode
con = u.urlopen(url)

page = str(con.read())
value3 = int(page.find("<title>")) + 7
value4 = int(page.find("</title>")) - 15
district = str(page[value3:value4])
print(district)
newdistrict = district.replace("\xe2\x80\x99","'")
print(newdistrict)
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我的代码以以下格式提取标题:IN-09: Indiana\xe2\x80\x99s 9th. 我知道\xe字符串是'符号的unicode ,但我不知道如何让 python 用'符号替换那组字符。我试过解码字符串,但它已经在 unicode 中,上面的替换代码不会改变任何东西。关于我做错了什么的任何建议?

Chr*_*gan 6

当您调用 时con.text(),这将返回一个bytes对象。调用str()它会返回一个表示它的字符串- 因此,如果您不指定编码,则使用转义符而不是实际字符。(这意味着您的字符串最终包含\\xe2\\x80\\x99以及各种其他不需要的东西。)bytesstrPython 2 中的情况大致相同:它没有存储任何编码信息。str在 Python 3 中就像unicode在 Python 2 中一样;它有编码。所以,当把一个bytes对象变成一个str对象时,你需要告诉它它实际上采用的是什么编码。在这种情况下,就是utf-8.

与其调用str()它,不如使用bytes.decode; 这是同样的事情,只是更整洁。

>>> import urllib.request as u
>>> zipcode = 47401
>>> url = 'http://watchdog.net/us/?zip={}'.format(zipcode)
>>> con = u.urlopen(url)
>>> page = con.read().decode('utf-8')
>>> page[page.find("<title>") + 7:page.find("</title>") - 15]
'IN-09: Indiana’s 9th'
Run Code Online (Sandbox Code Playgroud)

此处所做的唯一功能更改是将bytes对象解码为 的规范'utf-8'