CountVectorizer терпит неудачу из-за плохих слов

Я использую pandas dataFrame и пытаюсь получить количество вхождений слов для определенного столбца со строками. Код работает хорошо, пока какая-то строка со следующей ошибкой

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-36-af8291199984> in <module>
      6 
      7 cv = CountVectorizer(stop_words=None)
----> 8 cv_fit=cv.fit_transform(texts)
      9 word_list = cv.get_feature_names();
     10 count_list = cv_fit.toarray().sum(axis=0)

~/anaconda3/envs/turiCreate/lib/python3.8/site-packages/sklearn/feature_extraction/text.py in fit_transform(self, raw_documents, y)
   1196         max_features = self.max_features
   1197 
-> 1198         vocabulary, X = self._count_vocab(raw_documents,
   1199                                           self.fixed_vocabulary_)
   1200 

~/anaconda3/envs/turiCreate/lib/python3.8/site-packages/sklearn/feature_extraction/text.py in _count_vocab(self, raw_documents, fixed_vocab)
   1127             vocabulary = dict(vocabulary)
   1128             if not vocabulary:
-> 1129                 raise ValueError("empty vocabulary; perhaps the documents only"
   1130                                  " contain stop words")
   1131 

ValueError: empty vocabulary; perhaps the documents only contain stop words

И это мой код, обращающийся к этой строке:

import pandas as pd
import numpy as np    
from sklearn.feature_extraction.text import CountVectorizer

texts=[":)"]    

cv = CountVectorizer(stop_words=None)   
cv_fit=cv.fit_transform(texts)    
word_list = cv.get_feature_names();    
count_list = cv_fit.toarray().sum(axis=0)

print(word_list)
print(dict(zip(word_list,count_list)))

Как заставить CountVectorizer решить эту проблему?


person Abdelrahman Ahmad    schedule 20.10.2020    source источник


Ответы (1)


Проблема, с которой вы столкнулись, связана с шаблоном токенизации, указанным в token_pattern='(?u)\\b\\w\\w+\\b'. Вы можете адаптировать его под свою задачу:

import pandas as pd
import numpy as np    
from sklearn.feature_extraction.text import CountVectorizer

texts=["hello :)"]    

cv = CountVectorizer(stop_words=None, token_pattern=r'(?u)\b\w\w+\b|[:)]+')  
cv_fit=cv.fit_transform(texts)    
word_list = cv.get_feature_names();    
count_list = cv_fit.toarray().sum(axis=0)

print(word_list)
print(dict(zip(word_list,count_list)))
[':)', 'hello']
{':)': 1, 'hello': 1}

Если вас беспокоят смайлики, более надежным решением для ваших целей (как они говорят, индустриальных) может быть пробел:

import spacy
from spacymoji import Emoji
from collections import Counter
nlp = spacy.load('en_core_web_sm')
emoji = Emoji(nlp)
nlp.add_pipe(emoji, first=True)

tokens = [tok for tok in nlp.tokenizer("Hi :) ????")]
counts = Counter(tokens)
print(counts)
Counter({Hi: 1, :): 1, ????: 1})
person Sergey Bushmanov    schedule 20.10.2020
comment
Большое тебе спасибо. - person Abdelrahman Ahmad; 20.10.2020