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\xa359bn', 'Тереза Мэй', 'Брексит', 'Брексит', 'Мистер Клегг', 'Мистер Клегг', 'Мистер Клегг', 'Брексит', ' Мистер Клегг», «Тереза Мэй»]
А потом ошибка:
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)
Пробовал разные способы исправления юникода (в том числе и sys.setdefaultencoding('utf8')
), ничего не получалось. Я надеюсь, что у кого-то была такая же проблема раньше, и он сможет предложить решение. Благодарю вас!
text=u"{}".format(text)
, чтобы использовать вместо негоdecode(...)
. - person stovfl   schedule 07.05.2017from __future___ import ...
не будет работать, если она не находится в начале скрипта. - person alvas   schedule 10.05.2017