我正在尝试读取 html 文件,但是当寻找标题和 url 以与我的关键字 'alist'
进行比较时,我收到此错误 Unicode Encode Error: 'ascii' codec无法对字符 u'\u2019' 进行编码。
链接错误 ( http://tinypic.com/r/307w8bl/8 )
代码
for q in soup.find_all('a'):
title = (q.get('title'))
url = ((q.get('href')))
length = len(alist)
i = 0
while length > 0:
if alist[i] in str(title): #checks for keywords from html form from the titles and urls
r.write(title)
r.write("\n")
r.write(url)
r.write("\n")
i = i + 1
length = length -1
doc.close()
r.close()
一点背景。 alist 包含一个关键字列表,我将使用它与标题进行比较以获得我想要的内容。奇怪的是,如果 alist 包含 2 个或更多单词,它会完美运行,但如果只有一个单词,就会出现如上所示的错误。 提前致谢。
最佳答案
如果您的列表必须是字符串列表,请尝试对标题 var 进行编码
>>> alist=['á'] #asci string
>>> title = u'á' #unicode string
>>> alist[0] in title
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
>>> title and alist[0] in title.encode('utf-8')
True
>>>
关于python - Unicode 编码错误 : 'ascii' codec can't encode character u'\u2019',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24737594/