1 回答
TA贡献1795条经验 获得超7个赞
有更好的方法来删除 TF-IDF 计算中的停用词。有TfidfVectorizer一个参数stop_words,您可以在其中传递要排除的单词集合。
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
documents = ['I went to the barbershop when my hair was long.', 'The barbershop was closed.']
# create set of stopwords to remove
stop_words = set(stopwords.words('italian'))
english_stop_words = set(stopwords.words('english'))
stop_words.update(english_stop_words)
# check if word in stop words
print('when' in stop_words) # True
print('il' in stop_words) # True
# else add word to the set
print('went' in stop_words) # False
stop_words.add('went')
# create tf-idf from original documents
tfidf = TfidfVectorizer(stop_words=stop_words)
x = tfidf.fit_transform(documents)
df_tfidf = pd.DataFrame(x.toarray(), columns=tfidf.get_feature_names())
print({c: s[s > 0] for c, s in zip(df_tfidf, df_tfidf.T.values)})
# {'barbershop': array([0.44943642, 0.57973867]), 'closed': array([0.81480247]), 'hair': array([0.6316672]), 'long': array([0.6316672])}
添加回答
举报