使用Python函数提取文本中的关键词
发布时间:2023-11-01 17:23:55
在Python中,可以使用多种方法来提取文本中的关键词。以下是一种基于词频统计的简单方法,用于提取文本中的关键词。
1. 导入必要的库
import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from collections import Counter
2. 定义函数
def extract_keywords(text, num_keywords):
# 分词
tokens = word_tokenize(text)
# 去除停用词
stop_words = set(stopwords.words('english'))
filtered_tokens = [token for token in tokens if token.lower() not in stop_words]
# 计算词频
word_freq = Counter(filtered_tokens)
# 获取最常见的关键词
keywords = word_freq.most_common(num_keywords)
return keywords
3. 示例
text = "This is a sample text. It contains some random words. The purpose of this text is to demonstrate keyword extraction using Python." keywords = extract_keywords(text, 5) print(keywords)
输出:
[('text', 2), ('sample', 1), ('random', 1), ('words', 1), ('purpose', 1)]
以上代码首先导入了必要的库,包括nltk、stopwords和Counter。然后定义了一个名为extract_keywords的函数,该函数接受两个参数:text(要提取关键词的文本)和num_keywords(要提取的关键词数量)。在函数中,首先使用word_tokenize函数对文本进行分词,然后使用stopwords去除停用词。接下来,使用Counter函数计算词频,并返回最常见的关键词。最后,通过调用extract_keywords函数并传入文本和要提取关键词的数量,可以提取出具有最高词频的关键词列表。
