python文本关键词提取
时间: 2023-05-24 21:05:31 浏览: 159
Python中的文本关键词提取可以使用以下几种方法:
1.基于频率的关键词提取
最简单的关键词提取方式是基于频率的方法。通过统计每个词在文本中出现的频率,选取出现频率最高的词作为关键词。可以用Python中的nltk库来实现,具体步骤如下:
```
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
text = "The quick brown fox jumps over the lazy dog. The quick brown fox is very fast."
stop_words = set(stopwords.words('english'))
# 分词
words = word_tokenize(text)
# 去除停用词
words = [word for word in words if word.lower() not in stop_words]
# 构建频率分布
freq_dist = nltk.FreqDist(words)
# 打印前20个关键词及其频次
for word, frequency in freq_dist.most_common(20):
print(u'{}:{}'.format(word, frequency))
```
2.基于TF-IDF的关键词提取
TF-IDF是一种基于词频和文档频率的算法,用于评估文本重要程度。在文本关键词提取中,可以使用TF-IDF算法来提取关键词。可以用Python中的scikit-learn库来实现,具体步骤如下:
```
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
text = ["The quick brown fox jumps over the lazy dog. The quick brown fox is very fast.",
"The lazy dog is very slow. The quick brown fox is very fast."]
# 初始化TF-IDF向量化器
tfidf_vectorizer = TfidfVectorizer(stop_words='english')
# 计算TF-IDF矩阵
tfidf_matrix = tfidf_vectorizer.fit_transform(text)
# 获取特征名
feature_names = tfidf_vectorizer.get_feature_names()
# 构建TF-IDF矩阵的数据框
tfidf_df = pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)
# 打印TF-IDF矩阵中的前20个关键词及其TF-IDF值
for i, row in tfidf_df.iterrows():
print(f"\nDocument {i+1}:")
print(row.nlargest(20))
```
3.基于LDA的关键词提取
LDA(Latent Dirichlet Allocation)是一种主题模型,可以将文本看作是由多个主题组成的。在文本关键词提取中,可以使用LDA算法来提取文本的主题以及与主题相关的关键词。可以用Python中的gensim库来实现,具体步骤如下:
```
import nltk
from gensim.models import LdaModel
from gensim.corpora import Dictionary
text = [["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."],
["The", "quick", "brown", "fox", "is", "very", "fast."],
["The", "lazy", "dog", "is", "very", "slow."]]
# 将单词转化为数字ID
documents = [Dictionary(text) for text in texts]
# 将文本转化为BoW向量
corpus = [dictionary.doc2bow(text) for text in texts]
# 训练LDA模型
lda_model = LdaModel(corpus=corpus, id2word=dictionary, num_topics=3)
# 打印LDA模型中的每个主题
for i in range(lda_model.num_topics):
print(f"Topic {i+1}:")
print(lda_model.print_topic(i))
```
以上三种方法提取出的文本关键词都可以在后续的文本分析任务中发挥重要作用。
阅读全文