英文词频统计
关键问题:
1、词语 -- 键
2、相同词语的累加 -- 值
讨论:定义什么数据类型 -- 字典类型
问题描述:
I:文件的输入
P:采用字典类型的结构统计词语出现的频率
O:每个单词及单词出现的次数(要求输出前10个)
IPO细化:
第一步:
(1) txt文件读取 -- txt.read("filename","r")
(2) 文件大小写的转换
(3) 特殊字符(各种标点符号)的替换
(4) 输出处理后的文件
——定义一个函数 #将文件进行格式化处理
第二步:对每个单词进行计数
(1) 定义一个字典类型的变量counts
(2) 单词在counts 中,单词定义的值 直接+1
(3) 单词不在counts 中,首先要将单词添加到字典中,然后并将其值赋值为1
第三步:
(1) 输出所用的键值对
(2) 输出排名前n的键值对
字典类型转换为列表类型
对列表类型用sort函数排序
按要求输出
第四步:
采用集合类型构建一个排除词汇库excludes
在输出结果中去掉冠词、代词、连接词等语法型词汇
# -*- coding:utf-8 -*-
excludes = {"the","and","of","you","a","i","my","in"}
def txt_sort():
txt = open("hamlet.txt", "r").read()
txt = txt.lower()
for i in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(i, " ")
return txt
hamletTxt = txt_sort()
words = hamletTxt.split()
counts = {} #新建一个空字典
for word in words:
counts[word] = counts.get(word, 0) + 1 #对单词出现的频率进行统计
for word in excludes:
del(counts[word])
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(10):
word, count = items[i] #返回相对应的键值对
print ("{0:<10}{1:>5}".format(word, count))