簡體   English   中英

Unicode編碼錯誤:'ascii'編解碼器無法編碼字符u'\\ u2019'

[英]Unicode Encode Error: 'ascii' codec can't encode character u'\u2019'

我正在嘗試閱讀html文件,但在尋找標題和網址以與我的關鍵字'alist'進行比較時,我得到此錯誤Unicode Encode Error: 'ascii' codec can't encode character u'\’'. 鏈接錯誤( 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個或更多單詞,它將完美運行但如果只有一個單詞,則會出現如上所示的錯誤。 提前致謝。

如果您的列表必須是字符串列表,請嘗試編碼title 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
>>> 

據推測, title是一個Unicode字符串,可以包含任何類型的字符; str(title)嘗試使用ASCII編解碼器將其轉換為字節串,但由於標題包含非ASCII字符,因此失敗。

你想做什么? 為什么需要將標題轉換為字節串?

問題出在str(title) 你正在嘗試將unicode數據轉換為字符串。

為什么你要將title轉換為字符串? 你可以直接訪問它。

soup.find_all將返回字符串列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM