我正在尝试运行一个Python代码,用于统计文本中某些预定义关键词的频率。然而,运行下面的脚本时,我得到的都是零(即脚本没有统计出目标文本中任何关键词的出现)。
似乎错误卡在了"X = vectorizer.fit_transform(text)"
这一行,因为它总是返回一个空的变量X。
在这个简短的例子中,我希望得到的结果是一个表格,列出每种冰淇淋口味的计数,每个口味占据一列,并显示各个计数的总和。
import pandas as pdfrom collections import Counterfrom sklearn.feature_extraction.text import CountVectorizericecream = ['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).A1freq_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)
如果你对这段代码可能存在的问题有任何想法,我将非常感谢你与我分享。谢谢!
回答:
由于你在参数中使用了lowercase=True
,所有找到的单词都会变成小写。但你的词汇表是这样的:
icecream = ['Vanilla', 'Strawberry', 'Chocolate', 'Peach']
这里的术语不会匹配它们的小写形式,所以一切都是0。你也应该把它们改成小写:
icecream = ['vanilla', 'strawberry', 'chocolate', 'peach']
之后的输出是这样的:
vanilla strawberry chocolate peach totalnumFranks Store 2 1 1 0 4.0
现在可以看到vanilla
的计数为2,因为它在文本中出现了两次。如果你只想统计某个口味是否存在,你可以在CountVectorizer
中使用binary=True
参数。