python-3.x 如何使CountVectorizer()忽略停用词而不管大小写

sdnqo3pr  于 2023-05-23  发布在  Python
关注(0)|答案(1)|浏览(136)

我使用Sklearn countvectorizer()是这样的

  1. vectorizer = CountVectorizer(
  2. stop_words="english",
  3. lowercase=False,
  4. ngram_range=ngram_range,
  5. )

我不想将我的文本转换为小写,但我想删除所有的停用词,无论情况如何。上面的代码过滤掉了the,但没有过滤掉TheTHE。我想过滤theTHEThe。是否可以通过CountVectorizer()实现而不改变大小写?

bqujaahr

bqujaahr1#

我不认为有一个简单的方法来覆盖停止字删除和只有停止字删除,但如果你通过一个自定义的分析器,你可以提供自己的停止字删除。
这是我能想到的最小的东西,它不会从分析器中删除任何功能:

  1. from sklearn.feature_extraction.text import CountVectorizer
  2. class CaseInsensitiveStopWordsAnalyzer:
  3. def set_cv(self, cv):
  4. self.cv = cv
  5. def remove_stop_words(self, stop_words, doc):
  6. stop_words = set(w.lower() for w in stop_words)
  7. return [w for w in doc if w.lower() not in stop_words]
  8. def __call__(self, doc):
  9. preprocessor = self.cv.build_preprocessor()
  10. tokenizer = self.cv.build_tokenizer()
  11. stop_words = self.cv.get_stop_words()
  12. ngrams = self.cv._word_ngrams
  13. if preprocessor is not None:
  14. doc = preprocessor(doc)
  15. if tokenizer is not None:
  16. doc = tokenizer(doc)
  17. if stop_words is not None:
  18. doc = self.remove_stop_words(stop_words, doc)
  19. if ngrams is not None:
  20. doc = ngrams(doc)
  21. return doc
  22. analyzer = CaseInsensitiveStopWordsAnalyzer()
  23. vectorizer = CountVectorizer(
  24. stop_words="english",
  25. lowercase=False,
  26. ngram_range=(1, 1),
  27. analyzer=analyzer,
  28. )
  29. analyzer.set_cv(vectorizer)
  30. documents = ['foo Bar bar the The']
  31. vectorizer.fit_transform(documents)
  32. print(vectorizer.vocabulary_)

输出:

  1. {'foo': 2, 'Bar': 0, 'bar': 1}

这可以删除theThe,而不会更改词汇表其余部分的大小写。

展开查看全部

相关问题