为了学习Python,最好还是直接从写代码入手,解决的问题如下:
统计英文文章的词频,并按词频从大到小输出。
设计Python知识点:文件操作、with ... as ...语句、字典数据结构、字典排序、字符串正则替换
代码如下:
#coding=utf-8
'''
Created on 2015年8月15日
统计一篇英文文章各个单词出现的词频,并按单次的词频从大到小输出
@author: minmin
'''
import re
import collections
'''
从文件中读取内容,统计词频
'''
def count_word(path):
result = {}
with open(path) as file_obj:
all_the_text = file_obj.read()
#大写转小写
all_the_text = all_the_text.lower()
#正则表达式替换特殊字符
all_the_text = re.sub("\"|,|\.", "", all_the_text)
for word in all_the_text.split():
if word not in result:
result[word] = 0
result[word] += 1
return result
'''
以词频倒序
'''
def sort_by_count(d):
#字典排序
d = collections.OrderedDict(sorted(d.items(), key = lambda t: -t[1]))
return d
if __name__ == '__main__':
file_name = "..\my father.txt"
dword = count_word(file_name)
dword = sort_by_count(dword)
for key,value in dword.items():
print key + ":%d" % value
输出结果:

代码我也放到GitHub上面了
本文介绍了一种使用Python进行英文文章词频统计的方法,通过文件操作读取文本内容,利用正则表达式清理数据,并采用字典数据结构及排序功能实现词频统计,最后输出按词频排序的单词。
:统计词频&spm=1001.2101.3001.5002&articleId=84737932&d=1&t=3&u=d3bdce3882a1412f8b605338e5bcee28)
7520

被折叠的 条评论
为什么被折叠?



