UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
這是我在嘗試清理使用spaCy從html頁面提取的名稱列表時遇到的錯誤。如何修復UnicodeDecodeError:'ascii'編解碼器無法解碼字節?
我的代碼:
import urllib
import requests
from bs4 import BeautifulSoup
import spacy
from spacy.en import English
from __future__ import unicode_literals
nlp_toolkit = English()
nlp = spacy.load('en')
def get_text(url):
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
# delete unwanted tags:
for s in soup(['figure', 'script', 'style']):
s.decompose()
# use separator to separate paragraphs and subtitles!
article_soup = [s.get_text(separator="\n", strip=True) for s in soup.find_all('div', {'class': 'story-body__inner'})]
text = ''.join(article_soup)
return text
# using spacy
def get_names(all_tags):
names=[]
for ent in all_tags.ents:
if ent.label_=="PERSON":
names.append(str(ent))
return names
def cleaning_names(names):
new_names = [s.strip("'s") for s in names] # remove 's' from names
myset = list(set(new_names)) #remove duplicates
return myset
def main():
url = "http://www.bbc.co.uk/news/uk-politics-39784164"
text=get_text(url)
text=u"{}".format(text)
all_tags = nlp(text)
names = get_person(all_tags)
print "names:"
print names
mynewlist = cleaning_names(names)
print mynewlist
if __name__ == '__main__':
main()
對於這個特定的網址,我得到的名字的名單,其中包括像£或字符$:
['Nick Clegg', 'Brexit', '\xc2\xa359bn', 'Theresa May', 'Brexit', 'Brexit', 'Mr Clegg', 'Mr Clegg', 'Mr Clegg', 'Brexit', 'Mr Clegg', 'Theresa May']
然後錯誤:
Traceback (most recent call last) <ipython-input-19-8582e806c94a> in <module>()
47
48 if __name__ == '__main__':
---> 49 main()
<ipython-input-19-8582e806c94a> in main()
43 print "names:"
44 print names
---> 45 mynewlist = cleaning_names(names)
46 print mynewlist
47
<ipython-input-19-8582e806c94a> in cleaning_names(names)
31
32 def cleaning_names(names):
---> 33 new_names = [s.strip("'s") for s in names] # remove 's' from names
34 myset = list(set(new_names)) #remove duplicates
35 return myset
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
我嘗試了修復unicode的不同方法(包括sys.setdefaultencoding('utf8')
),沒有任何工作。我希望以前有人有同樣的問題,並能夠提出修復建議。謝謝!
清理你的回溯。這是不可讀的。 – Kanak
不知道錯誤發生的位置,並且不會因爲庫而重現。如果您手動修復名稱列表,它會起作用嗎? – handle
您是否檢查過**相關的問題,如右圖所示? – handle