Python实现统计英文文章词频的方法分析
本文实例讲述了Python实现统计英文文章词频的方法。分享给大家供大家参考,具体如下:
应用介绍:
统计英文文章词频是很常见的需求,本文利用python实现。
思路分析:
1、把英文文章的每个单词放到列表里,并统计列表长度;
2、遍历列表,对每个单词出现的次数进行统计,并将结果存储在字典中;
3、利用步骤1中获得的列表长度,求出每个单词出现的频率,并将结果存储在频率字典中;
4、以字典键值对的“值”为标准,对字典进行排序,输出结果(也可利用切片输出频率最大或最小的特定几个,因为经过排序sorted()函数处理后,单词及其频率信息已经存储在元组中,所有元组再组成列表。)
代码实现:
fin=open('The_Magic_Skin_Honore_de_Balzac.txt')#thetxtisup #toyou lines=fin.readlines() fin.close() '''transformthearticleintowordlist ''' defwords_list(): chardigit='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' all_lines='' forlineinlines: one_line='' forchinline: ifchinchardigit: one_line=one_line+ch all_lines=all_lines+one_line returnall_lines.split() '''calculatethetotalnumberofarticlelist sisthearticlelist ''' deftotal_num(s): returnlen(s) '''calculatetheoccurrencetimesofeveryword tisthearticlelist ''' defword_dic(t): fre_dic=dict() foriinrange(len(t)): fre_dic[t[i]]=fre_dic.get(t[i],0)+1 returnfre_dic '''calculatetheoccurrencetimesofeveryword wisdictionaryoftheoccurrencetimesofeveryword ''' defword_fre(w): forkeyinw: w[key]=w[key]/total returnw '''sortthedictionary visthefrequencyofwords ''' defword_sort(v): sort_dic=sorted(v.items(),key=lambdae:e[1]) returnsort_dic '''Thisisentranceoffunctions outputisthetenwordswiththelargestfrequency ''' total=total_num(words_list()) print(word_sort(word_fre(word_dic(words_list())))[-10:])
PS:这里再为大家推荐2款相关统计工具供大家参考:
在线字数统计工具:
http://tools.jb51.net/code/zishutongji
在线字符统计与编辑工具:
http://tools.jb51.net/code/char_tongji
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。