python - Unicode 编码错误 : 'ascii' codec can't encode character u'\u2019'

标签 python unicode

我正在尝试读取 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/

相关文章:

php - 如何在德语元音变音 [äöü] 上 preg_match_all?

python - 使用转换函数将列值转换为 float

python - 如何通过更改另一个属性的值来更改一个属性的值? (依赖属性)

python - 当鼠标单击远离 Tkinter 窗口时如何关闭 Tkinter 窗口?

java - 匹配所有内容包括unicode标点符号的正则表达式

Perl LWP::UserAgent 错误处理 UTF-8 响应

python - 两组数据的匹配指标

python - 如何像在 R 中一样在 IDLE 中获取最后执行的命令?

c++ - 是否可以在 Linux 和 Windows 上计算 EM DASH?

sql - 在脚本中将 N 放在字符串前面有什么缺点吗?它被认为是 "best practice"吗?