【问题标题】:CountVectorizer giving wrong counts for words?CountVectorizer 给出错误的单词计数?
【发布时间】:2017-12-19 16:06:21
【问题描述】:

假设我的文本文件包含以下文本:

敏捷的棕色狐狸跳过了懒惰的狗。一针及时节省 九。快速的棕色针迹跳过了懒惰的时间。里面的狐狸 时间可以救狗。

我想使用 sk-learn 的 CountVectorizer 来获取文件中所有单词的字数。 (我知道还有其他方法可以做到这一点,但我想使用 CountVectorizer 有几个原因。)这是我的代码:

from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer

text = input('Please enter the filepath for the text: ') 
text = open(text, 'r', encoding = 'utf-8')
tokens = CountVectorizer(analyzer = 'word', stop_words = 'english')


X = tokens.fit_transform(text)
dictionary = tokens.vocabulary_

除了当我打电话给dictionary 时,它给了我错误的计数:

>>> dictionary
{'time': 9, 'dog': 1, 'stitch': 8, 'quick': 6, 'lazy': 5, 'brown': 0, 'saves': 7, 'jumped': 4, 'fox': 3, 'dogs': 2}

任何人都可以就我在这里犯的(无疑是显而易见的)错误提出建议吗?

【问题讨论】:

    标签: python scikit-learn nlp nltk countvectorizer


    【解决方案1】:

    vocabulary_ 是术语到它们在文档术语矩阵中的索引的字典/映射,而不是计数:

    vocabulary_:术语到特征索引的映射。

    X 实际上为您提供了特征索引和相应计数的矩阵。

    >>> for i in X:
    ...    print(i)
    ... 
      (0, 1)    1
      (0, 7)    2
      (0, 9)    3
      (0, 8)    2
      (0, 2)    1
      (0, 5)    2
      (0, 4)    2
      (0, 3)    2
      (0, 0)    2
      (0, 6)    2
    

    例如9 -> 'time' 的计数为 3。

    【讨论】:

    • 啊,我明白了!确实感谢这个非常简洁的解决方案。
    猜你喜欢
    • 2016-08-15
    • 2020-12-01
    • 2017-10-11
    • 1970-01-01
    • 2018-08-04
    • 2018-08-31
    • 1970-01-01
    • 2018-09-12
    • 2017-10-12
    相关资源
    最近更新 更多