本文实例讲述了Python实现统计英文文章词频的方法。分享给大家供大家参考,具体如下:
应用介绍:
统计英文文章词频是很常见的需求,本文利用python实现。
思路分析:
1、把英文文章的每个单词放到列表里,并统计列表长度;
2、遍历列表,对每个单词出现的次数进行统计,并将结果存储在字典中;
3、利用步骤1中获得的列表长度,求出每个单词出现的频率,并将结果存储在频率字典中;
4、以字典键值对的“值”为标准,对字典进行排序,输出结果(也可利用切片输出频率最大或最小的特定几个,因为经过排序sorted()函数处理后,单词及其频率信息已经存储在元组中,所有元组再组成列表。)
代码实现:
fin = open('The_Magic_Skin _Honore_de_Balzac.txt') #the txt is up #to you lines=fin.readlines() fin.close() '''transform the article into word list ''' def words_list(): chardigit='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ' all_lines = '' for line in lines: one_line='' for ch in line: if ch in chardigit: one_line = one_line + ch all_lines = all_lines + one_line return all_lines.split() '''calculate the total number of article list s is the article list ''' def total_num(s): return len(s) '''calculate the occurrence times of every word t is the article list ''' def word_dic(t): fre_dic = dict() for i in range(len(t)): fre_dic[t[i]] = fre_dic.get(t[i],0) + 1 return fre_dic '''calculate the occurrence times of every word w is dictionary of the occurrence times of every word ''' def word_fre(w): for key in w: w[key] = w[key] / total return w '''sort the dictionary v is the frequency of words ''' def word_sort(v): sort_dic = sorted(v.items(), key = lambda e:e[1]) return sort_dic '''This is entrance of functions output is the ten words with the largest frequency ''' 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程序设计有所帮助。
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]