2

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

敏捷的棕色狐狸跳过了懒惰的狗。小洞不补,大洞吃苦。快速的棕色针迹跳过了懒惰的时间。狐狸及时救了一条狗。

我想使用 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}

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

4

1 回答 1

6

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。

于 2017-07-14T14:13:21.867 回答