使用nltk库提取关键词

2 投票
1 回答
3343 浏览
提问于 2025-04-16 19:09

我正在开发一个应用程序,需要从一系列对话中提取关键词(最后生成这些词的标签云)。我考虑了以下几个步骤:

  1. 把每段原始对话分成一个个小部分(结果存储为字符串的列表的列表)
  2. 去掉一些常见的无意义词汇
  3. 使用词干提取工具(比如Porter词干算法)

到这里为止,nltk提供了我需要的所有工具。不过接下来,我需要对这些词进行“排名”,找出最重要的词。有没有人能推荐一下nltk中可以用来做这个的工具?

谢谢,Nihit

1 个回答

3

我想这要看你怎么理解“重要”这个词。如果你是说出现的频率,那么你可以用单词(或者词根)作为字典的键,然后用出现的次数作为值来建立一个字典。之后,你可以根据这些值对字典里的键进行排序。

大概是这样的(没有测试过):

from collections import defaultdict

#Collect word statistics
counts = defaultdict(int) 
for sent in stemmed_sentences:
   for stem in sent:
      counts[stem] += 1

#This block deletes all words with count <3
#They are not relevant and sorting will be way faster
pairs = [(x,y) for x,y in counts.items() if y >= 3]

#Sort (stem,count) pairs based on count 
sorted_stems = sorted(pairs, key = lambda x: x[1])

撰写回答