我有以下由以下代码生成的单词频率列表。
Frequency
the 3
15 5
18 1
a 1
2020 4
... ...
house 1
apartment 1
hotel 5
pool 1
swimming 1
代码是
from sklearn.feature_extraction.text import CountVectorizer
word_vectorizer = CountVectorizer(ngram_range=(1,1), analyzer='word')
sparse_matrix = word_vectorizer.fit_transform(df['Sentences'])
w_freq = sum(sparse_matrix).toarray()[0]
w_df=pd.DataFrame(w_freq, index=word_vectorizer.get_feature_names(), columns=['Frequency'])
w_df
我想从上面的单词列表中删除停用词(不是在我的数据帧列中,而只是在输出中,创建一个新变量以备不时之需(。
我已经尝试过w_df =[w for w in w_df if not w in stop_words]
但它给了我['Frequency']
作为输出。 我认为发生这种情况是因为它不是一个列表。 你能告诉我如何从那里删除停用词(包括数字(吗? 谢谢
CountVectorizer
有一个参数可以为您执行此操作。您可以为其提供自定义非索引字列表,或将其设置为english
,内置停用词列表。下面是一个示例:
s = pd.Series('Just a random sentence with more than one stopword')
word_vectorizer = CountVectorizer(ngram_range=(1,1),
analyzer='word',
stop_words='english')
sparse_matrix = word_vectorizer.fit_transform(s)
w_freq = sum(sparse_matrix).toarray()[0]
w_df=pd.DataFrame(w_freq,
index=word_vectorizer.get_feature_names(),
columns=['Frequency'])
print(w_df)
Frequency
just 1
random 1
sentence 1
stopword 1
补充一点,你的方法并没有那么错。你只需要一个小小的改变。
w_df = [w for w in w_df.index if not w in stop_words]
您的问题很简单,在列表理解中,您迭代了数据帧本身,而不是其索引中的令牌。这也将返回所需的结果。