【问题标题】:How to ignore some words when counting the frequency of a word accuracy in a text?在计算文本中单词准确率的频率时如何忽略某些单词?
【发布时间】:2015-12-22 11:14:56
【问题描述】:
在计算文本中单词准确度的频率时,如何忽略“a”、“the”等单词?
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
df= pd.DataFrame({'phrase': pd.Series('The large distance between cities. The small distance. The')})
f = CountVectorizer().build_tokenizer()(str(df['phrase']))
result = collections.Counter(f).most_common(1)
print result
答案将是该。但我想将 distance 作为最常用的词。
【问题讨论】:
标签:
python
python-2.7
text
pandas
scikit-learn
【解决方案1】:
最好避免这样计算开头的条目。
ignore = {'the','a','if','in','it','of','or'}
result = collections.Counter(x for x in f if x not in ignore).most_common(1)
【解决方案2】:
另一种选择是使用CountVectorizer 的stop_words 参数。
这些是您不感兴趣的词,将被分析器丢弃。
f = CountVectorizer(stop_words={'the','a','if','in','it','of','or'}).build_analyzer()(str(df['phrase']))
result = collections.Counter(f).most_common(1)
print result
[(u'distance', 1)]
请注意,tokenizer 不执行预处理(小写、重音去除)或删除停用词,因此您需要在此处使用分析器。
您还可以使用stop_words='english' 自动删除英语停用词(完整列表请参阅sklearn.feature_extraction.text.ENGLISH_STOP_WORDS)。