Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

html - Why won't Python display this text correctly? (UTF-8 Decoding Issue)

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("xe2x80x99","'")
print(newdistrict)

For some reason, my code is pulling in the title in the following format: IN-09: Indianaxe2x80x99s 9th. I know the xe string of characters is unicode for the ' symbol, but I can't figure out how to get python to replace that set of characters with the ' symbol. I've tried decoding the string but it's already in unicode and the replace code above doesn't change anything. Any advice as to what I'm doing incorrectly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you call con.text(), this returns a bytes object. Calling str() on it returns a string of the representation of it - thus, the escapes are used rather than the real characters, if you don't specify an encoding. (That means that your string ends up containing \xe2\x80\x99 as well as all sorts of other undesired things.) bytes is mostly like str in Python 2: it doesn't have any encoding information stored. str in Python 3 is like unicode in Python 2; it has the encoding. So, when turning a bytes object into a str object, you need to tell it what encoding it is actually in. In this case, that's utf-8.

Instead of calling str() on it, you would be better to use bytes.decode; it's the same thing, just neater.

>>> 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'

The only functional change that has been made here is the specification to decode the bytes object as 'utf-8'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...