从URL读取unicode中的文本文件?

Mic*_*ith 1 python urllib urllib2

我正在尝试使用urllib和urllib2来读取其中包含法语字符的文本文件,例如"é","à"等.

def load(url):
     from urllib2 import Request, urlopen, URLError, HTTPError

     req = Request(url)

     f = urlopen(req)
     f.readline()

     for line in f:
          line = line.split('\t')
          word = line[0].encode('utf-8')
Run Code Online (Sandbox Code Playgroud)

我有一种感觉,read()方法返回一个字节字符串,所以我使用encode('utf-8')来获取unicode值,但这给了我以下错误

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 6: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

有人能告诉我发生了什么事吗?任何帮助,将不胜感激.谢谢!

kin*_*all 5

是的,你正在从文件中读取字节.您必须做的是将字节串解码,而不是编码为Unicode.你看,它已经编码了.如果不是,你就不需要做任何事了.

word = unicode(line[0], "utf8")
Run Code Online (Sandbox Code Playgroud)

您必须指定文件中使用的编码.如果不是utf8,另一个好的嫌疑人可能会latin1.或者,您知道,因为它是一个Web文档,您可以从标题和/或其内容中删除文档的编码,但这有点超出了您的问题的范围.