UnicodeDecodeError: кодек «utf-8» не может декодировать байт 0x80 в позиции 3131: неверный стартовый байт в моем коде - PullRequest
0 голосов
/ 04 мая 2018

Когда я пытаюсь добавить приведенный ниже код, выдает ошибку.
Я установил каждый python модуль, включая nltk. Я добавил lxml nampy, но это не сработает. Я использую python3 , и в этом случае я изменил urllib2 на urllib.requests.
Пожалуйста, помогите мне найти решение.
Я запускаю это как

python index.py

Мой индексный файл приведен ниже. Это код:

from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import ssl
import os 
import nltk
from nltk.corpus import stopwords 
from nltk.tokenize import word_tokenize
import codecs 


def checkChar(token):
    for char in token:
        if(0 <= ord(char) and ord(char) <= 64) or (91 <= ord(char) and ord(char) <= 96) or (123 <= ord(char)):
            return False 
        else:
            continue

    return True 

def cleanMe(html):
    soup = BeautifulSoup(html, "html.parser")
    for script in soup(["script, style"]):
        script.extract()

    text = soup.get_text()

    lines = (line.strip() for line in text.splitlines())

    chunks = (phrase.strip() for line in lines for phrase in line.split(" "))

    text = '\n'.join(chunk for chunk in chunks if chunk)

    return text

path = 'crawled_html_pages/'
index = {}
docNum = 0 
stop_words = set(stopwords.words('english'))

for filename in os.listdir(path):

    collection = {}

    docNum += 1

    file = codecs.open('crawled_html_pages/' + filename, 'r', 'utf-8')

    page_text = cleanMe(file)

    tokens = nltk.word_tokenize(page_text)

    filtered_sentence = [w for w in tokens if not w in stop_words]

    filtered_sentence = []

    breakWord = ''

    for w in tokens:
        if w not in stop_words:
            filtered_sentence.append(w.lower())

    for token in filtered_sentence:
        if len(token) == 1 or token == 'and':
            continue
        if checkChar(token) == false:
            continue
        if token == 'giants':
            breakWord = token
            continue
        if token == 'brady' and breakWord == 'giants':
            break
        if token not in collection:
            collection[token] = 0
        collection[token] += 1

    for token in collection:
        if tokennot in index:
            index[token] = ''
        index[token] = index[token] + '(' + str(docNum) + ', ' + str(collection[token]) + ")"

    if docNum == 500:
        print(index)
        break
    else:
        continue

    f = open('index.txt', 'w')
    vocab = open('uniqueWords.txt', 'w')
    for term in index:
    f.write(term + ' =>' + index[term])
    vocab.write(term + '\n')
    f.write('\n')
    f.close()
    vocab.close()

     print('Finished...')

Вот ошибки, которые я получаю:

C: \ Users \ myworld> python index.py
Traceback (последний вызов был последним):
Файл "index.py] [1]", строка 49, в
page_text = cleanMe (файл)
Файл "index.py", строка 22, в cleanMe
суп = BeautifulSoup (html, "html.parser")
Файл "C: \ Users \ furqa \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ site-packages \ beautifulsoup4-4.6.0-py3.6.egg \ bs4__init __. Py", строка 191, в * INIT 1028 *
Файл "C: \ Users \ furqa \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ codecs.py", строка 700, для чтения
вернуть self.reader.read (размер)
Файл "C: \ Users \ furqa \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ codecs.py", строка 503, для чтения
newchars, decodedbytes = self.decode (data, self.errors) UnicodeDecodeError: кодек «utf-8» не может декодировать байт 0x80 в позиции 3131: неверный стартовый байт

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...