当前位置:   article > 正文

【Python】统计文本中单词的出现次数前十的单词_python统计出现频率最高的10个单词

python统计出现频率最高的10个单词

代码:

  1. # 读取一个文本,并且统计文本中单词的出现次数
  2. def read_file():
  3. # 在windows环境中的编码问题,指定utf-8
  4. with open('F:/python源码/实验区/002.txt', 'r', encoding='utf-8') as f:
  5. word = [] # 空列表用来存储文本中的单词
  6. # readlins为分行读取文本,且返回的是一个列表,每行的数据作为列表中的一个元素:
  7. for word_str in f.readlines(): # 如:["In this article, you will learn about Python closures, understand ",...]
  8. # 因为原文中每个单词都是用空格 或者逗号加空格分开的,去除原文中的逗号
  9. word_str = word_str.replace(',', '')
  10. # strip去除每行字符串数据两边的空白字符
  11. word_str = word_str.strip()
  12. # 对单行字符串通过空格进行分割,返回一个列表
  13. word_list = word_str.split(' ')
  14. # 将分割后的列表内容,添加到word空列表中
  15. word.extend(word_list)
  16. return word
  17. def clear_account(lists):
  18. # 定义空字典,用来存放单词和对应的出现次数
  19. count_dict = {}
  20. # count_dict是这种形式{'': None, 'LEARN': None, 'CODING': None, 'FROM': None......}
  21. count_dict = count_dict.fromkeys(lists) # 现在的lists是一个没有去重,包含所有单词的列表
  22. # 取出字典中的key,放到word_list1(去重后的列表中)
  23. word_list1 = list(count_dict.keys())
  24. # 然后统计单词出现的次数,并将它存入count_dict字典中
  25. for i in word_list1:
  26. # lists为没有去重的那个列表,即包含所有重复单词的列表,使用count得到单词出现次数,作为value
  27. count_dict[i] = lists.count(i)
  28. return count_dict
  29. def sort_dict(count_dict):
  30. # 删除字典中''单词
  31. del [count_dict['']]
  32. # 排序,按values进行排序,如果是按key进行排序用sorted(wokey.items(),key=lambda d:d[0],reverse=True)
  33. # 使用lambda匿名函数用value排序,返回列表[('the', 45), ('function', 38)...这种形式]
  34. my_dict = sorted(count_dict.items(), key=lambda d:d[1], reverse=True) # 临时参数d[1]是用value排序
  35. # 将列表转成字典<class 'dict'>
  36. my_dict = dict(my_dict)
  37. return my_dict
  38. def main(my_dict):
  39. # 输出前10个
  40. i = 0
  41. # .items返回一个包含所有(键,值)元祖的列表
  42. for x, y in my_dict.items():
  43. if i < 10:
  44. # print('the word is "', '{}'.format(x), '"', ' and its amount is "', '{}'.format(y), '"')
  45. print('单词"%s",出现次数为 %s' %(x,y) )
  46. i += 1
  47. continue
  48. else:
  49. break
  50. # 执行函数
  51. main(sort_dict(clear_account(read_file())))

 

 

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号