如何在计算文本中单词准确度的频率时忽略某些单词?

How to ignore some words when counting the frequency of a word accuracy in a text?

如何在计算文本中单词准确度的频率时忽略'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 作为最常见的词。

最好避免像这样开始计数条目。

ignore = {'the','a','if','in','it','of','or'}
result = collections.Counter(x for x in f if x not in ignore).most_common(1)

另一种选择是使用 CountVectorizerstop_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)。