Как я могу исправить "TypeError: ожидаемая строка или байтовоподобный объект" - PullRequest
0 голосов
/ 26 января 2019

Привет всем, у меня есть список текстовых документов (text_data), и я хочу векторизовать его, но он выдает ошибку TypeError: expected string or bytes-like object.Когда я звоню только preprocess(text_data) без tfidfconverter, это работает.Я не могу найти проблему, может кто-нибудь помочь мне, пожалуйста?

def preprocess(x):
    documents = []
    for sen in range(0, len(x)):

        # Remove all the special characters
        document = re.sub(r'\W', ' ', str(x[sen]))

        # Remove all numbers
        document = re.sub(r'[0-9]', ' ', document)

        # Remove all underscores
        document = re.sub(r'_', ' ', document)

        # remove all single characters
        document = re.sub(r'\s+[a-zA-Z]\s+', ' ', document)

        # Remove single characters from the start
        document = re.sub(r'\^[a-zA-Z]\s+', ' ', document)

        # Substituting multiple spaces with single space
        document = re.sub(r'\s+', ' ', document, flags=re.I)

        # Converting to Lowercase
        document = document.lower()

        # Lemmatization
        document = document.split()

        document = ' '.join([stemmer.stem(word) for word in document])
        documents.append(document)

    x = documents

tfidfconverter = TfidfVectorizer(min_df=10, max_df=0.97, stop_words=text.ENGLISH_STOP_WORDS, preprocessor=preprocess)

Traceback:

 Traceback (most recent call last):
 File "C:/Users/Konrad/PycharmProjects/treffen/treffen.py", line 54, in <module>
tfidf_table = tfidfconverter.fit_transform(text_data).toarray()
File "C:\Users\Konrad\PycharmProjects\treffen\venv\lib\site-packages\sklearn\feature_extraction\text.py", line 1603, in fit_transform
X = super(TfidfVectorizer, self).fit_transform(raw_documents)
File "C:\Users\Konrad\PycharmProjects\treffen\venv\lib\site-packages\sklearn\feature_extraction\text.py", line 1032, in fit_transform
self.fixed_vocabulary_)
File "C:\Users\Konrad\PycharmProjects\treffen\venv\lib\site-packages\sklearn\feature_extraction\text.py", line 942, in _count_vocab
for feature in analyze(doc):
File "C:\Users\Konrad\PycharmProjects\treffen\venv\lib\site-packages\sklearn\feature_extraction\text.py", line 328, in <lambda>
tokenize(preprocess(self.decode(doc))), stop_words)
File "C:\Users\Konrad\PycharmProjects\treffen\venv\lib\site-packages\sklearn\feature_extraction\text.py", line 265, in <lambda>
return lambda doc: token_pattern.findall(doc)
TypeError: expected string or bytes-like object

Process finished with exit code 1

1 Ответ

0 голосов
/ 08 июля 2019

Первая проблема, которую я вижу, заключается в том, что препроцессор ожидает возврата строки.Во-вторых, вам не нужно восстанавливать список documents, так как ваша функция препроцессора будет вызываться для каждой строки в вашем списке обучающих документов.Вы можете попробовать что-то вроде этого:

def preprocess(x):
    # Remove all the special characters
    document = re.sub(r'\W', ' ', str(x[sen]))

    # Remove all numbers
    document = re.sub(r'[0-9]', ' ', document)

    # Remove all underscores
    document = re.sub(r'_', ' ', document)

    # remove all single characters
    document = re.sub(r'\s+[a-zA-Z]\s+', ' ', document)

    # Remove single characters from the start
    document = re.sub(r'\^[a-zA-Z]\s+', ' ', document)

    # Substituting multiple spaces with single space
    document = re.sub(r'\s+', ' ', document, flags=re.I)

    # Converting to Lowercase
    document = document.lower()

    # Lemmatization
    document = document.split()
    document = ' '.join([stemmer.stem(word) for word in document]) 

    return document


tfidfconverter = TfidfVectorizer(min_df=10, max_df=0.97, stop_words=text.ENGLISH_STOP_WORDS, preprocessor=preprocess)
...