假设我的文本文件包含以下文本:
敏捷的棕色狐狸跳过了懒惰的狗。小洞不补,大洞吃苦。快速的棕色针迹跳过了懒惰的时间。狐狸及时救了一条狗。
我想使用 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}
任何人都可以就我在这里犯的(无疑是显而易见的)错误提出建议吗?