删除在语料库Python中出现超过x%的单词

问题描述 投票:0回答:1

我正在处理大量语料库,形式为标记/单词列表。语料库包含〜1900,000个单词,我运行了一个代码以获取最常用的单词,现在语料库中已有140,000个单词。

我想删除出现在文档中95%以上且少于5%的单词

语料样本

['problems', 'guess', 'sleep', 'holy']

首先我找到最常用的单词

from nltk.probability import FreqDist

corpus_frequency = FreqDist(corpus)

corpus_commom=corpus_frequency.most_common()

然后,我将此for循环应用于查找出现率超过95%的单词列表

most_frequent=[mytuple for mytuple in corpus_commom if mytuple[1]<len(corpus*95)/100]

但是此代码需要很长时间才能运行,并且不会返回任何输出。

我也尝试遵循我找到的一些答案并应用CountVectorizer,但收到错误消息

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(min_df=0.05, max_df=0.95, lowercase=True) 
X = cv.fit_transform(corpus)

错误消息

ValueError: After pruning, no terms remain. Try a lower min_df or a higher max_df.

任何人都可以给我提示如何实现这一目标?谢谢

python for-loop text-processing
1个回答
0
投票

正如错误所暗示的,转换后您没有剩余的术语。也就是说,每个单词的出现率大于95%或小于5%。例如:

corpus = ['This is a good sentence',
          'This is a good sentence',
          'This is a good sentence',
          'This is a good sentence',
          'This is a good sentence']
cv = CountVectorizer(min_df=0.05, max_df=0.95) 
X = cv.fit_transform(corpus)

将引发相同的错误。但是,当您的语料库有1900,000个单词时,这没有任何意义。也许您可以检查您的语料库是否为CountVectorizer的有效参数。在https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html中查看更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.