【发布时间】:2022-07-25 19:12:41
【问题描述】:
我有一个数据框,df,以 text、cleaned_text 和 nouns 作为列名。 text 和 cleaned_text 包含字符串文档,nouns 是从 cleaned_text 列中提取的名词列表。 df.shape = (1927, 3).
我正在尝试计算 df 内所有文档的 TF-IDF 值仅适用于名词,不包括 spaCy 停用词。
我尝试了什么?
import spacy
from spacy.lang.en import English
nlp = spacy.load('en_core_web_sm')
# subclass to modify stop word lists recommended from spaCy version 3.0 onwards
excluded_stop_words = {'down'}
included_stop_words = {'dear', 'regards'}
class CustomEnglishDefaults(English.Defaults):
stop_words = English.Defaults.stop_words.copy()
stop_words -= excluded_stop_words
stop_words |= included_stop_words
class CustomEnglish(English):
Defaults = CustomEnglishDefaults
# function to extract nouns from cleaned_text column, excluding spaCy stowords.
nlp = CustomEnglish()
def nouns(text):
doc = nlp(text)
return [t for t in doc if t.pos_ in ['NOUN'] and not t.is_stop and not t.is_punct]
# calculate TF-IDF values for nouns, excluding spaCy stopwords.
from sklearn.feature_extraction.text import TfidfVectorizer
documents = df.cleaned_text
tfidf = TfidfVectorizer(stop_words=CustomEnglish)
X = tfidf.fit_transform(documents)
我期待什么?
我希望有一个按降序排列的元组列表的输出;
nouns = [('noun_1', tf-idf_1), ('noun_2', tf-idf_2), ...]。 nouns 中的所有名词都应与df.nouns 中的名词一致(这是为了检查我是否走对了路)。
我的问题是什么?
我对如何应用 TfidfVectorizer 以便仅计算从 cleaned_text 中提取的名词的 TF-IDF 值感到困惑。我也不确定 SkLearn TfidfVectorizer 是否可以按照我的预期计算 TF-IDF。
【问题讨论】:
标签: python-3.x list dataframe nlp spacy