【发布时间】:2019-05-15 21:35:01
【问题描述】:
我正在尝试运行一个 Python 代码来计算文本中某些预定义关键字的频率。但是,在运行下面发布的脚本时,我只会得到零(即脚本不计算目标文本中关键字的出现次数)。
错误似乎停留在 "X = vectorizer.fit_transform(text)" 行,因为它总是返回一个空变量 X。
在这个简短的示例中,我试图得到一个表格,其中在单独的列中列出了每种口味的冰淇淋的计数,然后是各个计数的总和。
import pandas as pd
from collections import Counter
from sklearn.feature_extraction.text import CountVectorizer
icecream = ['Vanilla', 'Strawberry', 'Chocolate', 'Peach']
vectorizer = CountVectorizer(vocabulary=icecream, encoding='utf8', lowercase=True, analyzer='word', decode_error='ignore', ngram_range=(1, 1))
dq = pd.DataFrame(columns=icecream)
vendor = 'Franks Store'
text = ['We offer Vanilla with Hazelnut, Vanilla with Coconut, Chocolate and Strawberry']
X = vectorizer.fit_transform(text)
vocab = vectorizer.get_feature_names()
counts = X.sum(axis=0).A1
freq_distribution = Counter(dict(zip(vocab, counts)))
allwords = dict(freq_distribution)
totalnum = sum(allwords.values())
allwords.update({'totalnum': totalnum})
dy = pd.DataFrame.from_dict(allwords, orient='index')
dy.columns = [vendor]
dy = dy.transpose()
dq = dy.append(dq, sort=False)
print(dq)
如果您知道此代码可能有什么问题,如果您与我分享,我将非常高兴。谢谢!
【问题讨论】:
标签: python machine-learning scikit-learn nlp