TF-IDF算法:用 Python 提炼财经新闻
共 2476字,需浏览 5分钟
·
2022-05-20 22:05
所有的字都用小写。 删除数字和首字母。 删除停顿词。 删除标点符号。 词义化。这意味着将该词还原为一个词的词根同义词。由于de输入 "pos",可以确定词根是来自形容词、动词还是名词。 删除常见的词,如“wall street”, “market”, “stock”, “share”, …
import nltk
from nltk.stem importWordNetLemmatizer
import re
stopwords = nltk.corpus.words('english')
lemmatizer = WordNetLemmatizer()
processed_text = re.sub('[^a-zA-Z]', ' ',original_text)
processed_text = processed_text.lower()
processed_text = processed_text.split()
processed_text = [lemmatizer.lemmatize(word, pos='a') for word in processed_text if word notin set(stopwords)]
processed_text = [lemmatizer.lemmatize(word, pos='v') for word in processed_text if word notin set(stopwords)]
processed_text = [lemmatizer.lemmatize(word, pos='n') for word in processed_text if word notin set(stopwords)]
processed_text = ' '.join(processed_text)
processed_text = re.sub('stock', '', processed_text)
TfidfVectorizer
模型。这允许我们设置关键特征的数量,我们将其设置为8个最大特征。
from sklearn.feature_extraction.text importTfidfVectorizer
tf_idf_model = TfidfVectorizer(max_features=8)
processed_text_tf = tf_idf_model.fit_transform(preprocessed_texts)
tf_idf_values = tf_idf_model.idf_
tf_idf_names = tf_idf_model.get_feature_names()
- 点击下方阅读原文加入社区会员 -