Python实现英文文章词频统计的完整流程与代码解析
本文详细解析了使用Python统计英文文章词频的实现方法。通过构建单词列表、统计词频并计算频率,最终利用sorted函数对结果进行排序输出。文中提供了完整的代码逻辑说明及关键函数实现,并推荐了在线字数统计工具,帮助开发者快速掌握文本数据处理技巧。
本文详细介绍了一种使用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:])
此外,这里推荐两款相关的在线统计工具供读者参考使用:
在线字数统计工具: http://tools.jb51.net/code/zishutongji
在线字符统计与编辑工具: http://tools.jb51.net/code/char_tongji
若读者对Python的其他操作技巧感兴趣,可进一步查阅本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》以及《Python入门与进阶经典教程》。
希望上述内容能对大家学习Python程序设计有所助益。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













