Python统计词频的方法有哪些

其他教程   发布日期:2023年07月21日   浏览次数:518

本文小编为大家详细介绍“Python统计词频的方法有哪些”,内容详细,步骤清晰,细节处理妥当,希望这篇“Python统计词频的方法有哪些”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

方法一:运用集合去重方法

  1. def word_count1(words,n):
  2. word_list = []
  3. for word in set(words):
  4. num = words.counts(word)
  5. word_list.append([word,num])
  6. word_list.sort(key=lambda x:x[1], reverse=True)
  7. for i in range(n):
  8. word, count = word_list[i]
  9. print('{0:<15}{1:>5}'.format(word, count))

说明:运用集合对文本字符串列表去重,这样统计词汇不会重复,运用列表的counts方法统计频数,将每个词汇和其出现的次数打包成一个列表加入到word_list中,运用列表的sort方法排序,大功告成。

方法二:运用字典统计

  1. def word_count2(words,n):
  2. counts = {}
  3. for word in words:
  4. if len(word) == 1:
  5. continue
  6. else:
  7. counts[word] = counts.get(word, 0) + 1
  8. items = list(counts.items())
  9. items.sort(key=lambda x:x[1], reverse=True)
  10. for i in range(n):
  11. word, count = items[i]
  12. print("{0:<15}{1:>5}".format(word, count))

方法三:使用计数器

  1. def word_count3(words,n):
  2. from collections import Counter
  3. counts = Counter(words)
  4. for ch in "": # 删除一些不需要统计的元素
  5. del counts[ch]
  6. for word, count in counts.most_common(n): # 已经按数量大小排好了
  7. print("{0:<15}{1:>5}".format(word, count))

以上就是Python统计词频的方法有哪些的详细内容,更多关于Python统计词频的方法有哪些的资料请关注九品源码其它相关文章!