【发布时间】:2017-10-05 15:23:37
【问题描述】:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
这是我在尝试清理我使用 spaCy 从 html 页面中提取的名称列表时遇到的错误。
我的代码:
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()
对于这个特定的 URL,我会得到包含 £ 或 $ 等字符的名称列表:
['尼克克莱格','英国脱欧','\xc2\xa3590亿','特蕾莎梅','英国脱欧', “英国脱欧”、“克莱格先生”、“克莱格先生”、“克莱格先生”、“英国退欧”、“克莱格先生”、 '特蕾莎梅']
然后报错:
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')),但没有任何效果。我希望有人以前遇到过同样的问题,并且能够提出修复建议。谢谢!
【问题讨论】:
-
清理你的回溯。不可读。
-
不确定错误发生在哪里,并且由于库而不会重现。如果您手动修复名称列表是否有效?
-
您是否检查了右侧显示的相关问题?
-
我检查了相关问题,但找不到适合我的案例的解决方案。我还尝试在将名称列表传递给清理函数之前对其进行操作,但再次对其进行解码和编码并没有帮助。
-
将此
text=u"{}".format(text)改为使用decode(...)。
标签: python-2.7 unicode beautifulsoup spacy