【python】入门学习(十)
#入门学习系列的内容均是在学习《Python编程入门(第3版)》时的学习笔记
统计一个文本文档的信息,并输出出现频率最高的10个单词
#text.py
#保留的字符
keep = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'
'q','r','s','t','u','v','w','x','y','z',' ','-',"'"}
#将文本规范化
def normalize(s):
"""Convert s to a normalized string."""
result = ''
for c in s.lower():
if c in keep:
result += c
return result #获取文本基本信息
def file_stats(fname):
"""Print statistics for the given file."""
s = open(fname,'r').read()
num_chars = len(s)
num_lines = s.count('\n')
num_words = len(normalize(s).split())
print("The file %s has:" % fname)
print(" %s characters" % num_chars)
print(" %s lines" % num_lines)
print(" %s words" % num_words) #将字符串转化为字典
def make_freq_dict(s):
"""Return a dictionary whose keys are the words of s,and whose values are the counts of those words."""
s = normalize(s)
words = s.split()
d = {}
for w in words:
if w in d:
d[w] += 1
else:
d[w] = 1
return d #获取文本基本信息
def file_stats2(fname):
"""Print statistics for the given file."""
s = open(fname,'r').read()
num_chars = len(s)
num_lines = s.count('\n')
d = make_freq_dict(s)
num_words = sum(d[w] for w in d)
lst = [(d[w],w) for w in d]
lst.sort()
lst.reverse()
print("The file %s has:" % fname)
print(" %s characters" % num_chars)
print(" %s lines" % num_lines)
print(" %s words" % num_words)
print("\nThe top 10 most frequent words are:")
i = 1
for count,word in lst[:99]:
print('%2s. %4s %s' % (i, count, word))
i += 1
>>> file_stats2('a.txt')
The file a.txt has:
12927 characters
297 lines
1645 words The top 10 most frequent words are:
1. 62 to
2. 62 the
3. 47 is
4. 42 a
5. 41 of
6. 40 it
7. 36 that
8. 35 and
9. 32 as
10. 24 so
进一步完善的代码:
#text.py
#保留的字符
keep = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'
'q','r','s','t','u','v','w','x','y','z',' ','-',"'"}
#将文本规范化
def normalize(s):
"""Convert s to a normalized string."""
result = ''
for c in s.lower():
if c in keep:
result += c
return result #获取文本基本信息
def file_stats(fname):
"""Print statistics for the given file."""
s = open(fname,'r').read()
num_chars = len(s)
num_lines = s.count('\n')
num_words = len(normalize(s).split())
print("The file %s has:" % fname)
print(" %s characters" % num_chars)
print(" %s lines" % num_lines)
print(" %s words" % num_words) #将字符串转化为字典
def make_freq_dict(s):
"""Return a dictionary whose keys are the words of s,and whose values are the counts of those words."""
s = normalize(s)
words = s.split()
d = {}
for w in words:
if w in d:
d[w] += 1
else:
d[w] = 1
return d #获取文本基本信息
def file_stats2(fname):
"""Print statistics for the given file."""
s = open(fname,'r').read()
num_chars = len(s)
num_lines = s.count('\n')
d = make_freq_dict(s)
num_different_words = sum(d[w]/d[w] for w in d)
num_words = sum(d[w] for w in d)
words_average_length = sum(len(w) for w in d)/num_different_words
num_once = sum(d[w] for w in d if d[w] == 1)
lst = [(d[w],w) for w in d]
lst.sort()
lst.reverse()
print("The file %s has:" % fname)
print(" %s characters" % num_chars)
print(" %s lines" % num_lines)
print(" %s words" % num_words)
print(" %s words appreance one time" % num_once)
print(" %s different words" % int(num_different_words))
print(" %s average length" % words_average_length)
print("\nThe top 10 most frequent words are:")
i = 1
for count,word in lst[:10]:
print('%2s. %4s %s' % (i, count, word))
i += 1 def main():
file_stats2('a.txt') if __name__=='__main__':
main()
>>> ================================ RESTART ================================
>>>
The file a.txt has:
12927 characters
297 lines
1645 words
515 words appreance one time
699 different words
6.539341917024321 average length The top 10 most frequent words are:
1. 62 to
2. 62 the
3. 47 is
4. 42 a
5. 41 of
6. 40 it
7. 36 that
8. 35 and
9. 32 as
10. 24 so
【python】入门学习(十)的更多相关文章
- python入门学习:9.文件和异常
python入门学习:9.文件和异常 关键点:文件.异常 9.1 从文件中读取数据9.2 写入文件9.3 异常9.4 存储数据 9.1 从文件中读取数据 9.1.1 读取整个文件 首先创建一个pi_ ...
- python入门学习:8.类
python入门学习:8.类 关键点:类 8.1 创建和使用类8.2 使用类和实例8.3 继承8.4 导入类 8.1 创建和使用类 面向对象编程是最有效的软件编写方法之一.在面向对象编程中,你编写 ...
- python入门学习:7.函数
python入门学习:7.函数 关键点:函数 7.1 定义函数7.2 传递实参7.3 返回值7.4 传递列表7.5 传递任意数量的实参7.6 将函数存储在模块中 7.1 定义函数 使用关键字def ...
- python入门学习:6.用户输入和while循环
python入门学习:6.用户输入和while循环 关键点:输入.while循环 6.1 函数input()工作原理6.2 while循环简介6.3 使用while循环处理字典和列表 6.1 函数in ...
- python入门学习:5.字典
python入门学习:5.字典 关键点:字典 5.1 使用字典5.2 遍历字典5.3 嵌套 5.1 使用字典 在python中字典是一系列键-值对.每个键都和一个值关联,你可以使用键来访问与之相关 ...
- python入门学习:4.if语句
python入门学习:4.if语句 关键点:判断 4.1 一个简单的测试4.2 条件测试4.3 if语句 4.1 一个简单的测试 if语句基本格式如下,注意不要漏了冒号 1if 条件 :2 ...
- python入门学习:3.操作列表
python入门学习:3.操作列表 关键点:列表 3.1 遍历整个列表3.2 创建数值列表3.3 使用列表3.4 元组 3.1 遍历整个列表 循环这种概念很重要,因为它是计算机自动完成重复工作的常 ...
- python入门学习:2.列表简介
python入门学习:2.列表简介 关键点:列表 2.1 列表是什么2.2 修改.添加和删除元素2.3 组织列表 2.1 列表是什么 列表,是由一系列按特定顺序排列的元素组成.你可以创建包含字母表 ...
- Python入门学习:1.变量和简单的数据类型
python入门学习:1.变量和简单的数据类型 关键点:变量.字符串.数字 1.1 变量的命名和使用1.2 字符串1.3 数字1.4 注释 1.1 变量的命名和使用 变量,顾名思义是一个可变的量, ...
- Python入门学习之路,怎么 “开心,高效,踏实” 地把Python学好?兴趣,兴趣,兴趣!
Python入门学习之路,怎么 “开心,高效,踏实” 地把Python学好?兴趣,兴趣,兴趣!找到你自己感兴趣的点进行切入,并找到兴趣点进行自我驱动是最好的学习方式! 推荐两本书,一本作为 ...
随机推荐
- JS keycode 事件响应
<script language="javascript"> function keyevent(){ if(event.keyCode==13) alert(&quo ...
- AngularJS API之extend扩展对象
angular.extend(dst,src),在我实验的1.2.16版本上是支持深拷贝的.但是最新的API显示,这个方法是不支持深拷贝的. 另外,第二个参数src支持多个对象. 第一种使用方式 va ...
- 大型网站SEO优化策略框架
- Linux下查看nginx安装目录
输入命令行: ps -ef | grep nginx master process后边的目录即是.
- DAY5 php + mysql 写一个简单的sql注入平台
php mysql 在浏览器输入用户名,去数据库查询.查到则显示在浏览器,查不到则显示空. sql 里面三个字段 id username password create table t1 (id in ...
- jquery 平滑锚
setTimeout('$("html,body").animate({ scrollTop: $(".title").offset().top }, 1000 ...
- Android学习笔记(十二)——实战:制作一个聊天界面
//此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! 运用简单的布局知识,我们可以来尝试制作一个聊天界面. 一.制作 Nine-Patch 图片 : Nine-Pa ...
- cocos2d界面渲染
渲染是visit函数来做的, visit是先将不可见的节点和他所有的子节点都跳过, 然后再看节点的子节点是否为空, 如果为空的话直接看这个节点是否在摄像机可见范围之内, 如果在就渲染这个节点, 否则什 ...
- OOP感想
OOP是面向对象编程(Object Oriented Programming).集于一身,最终目的是各司其职,让每个职责的只关注自己那块,其他的不管丢给下一个人.比如说,一个页面,对于客户,只要能看到 ...
- Unity3D绑定button监听事件
一.可视化创建及事件绑定 第一步:通过Hierarchy面板创建button,如图 第二步:创建一个脚本名为TestClick,并定义一个名为Click的public方法 ? 1 2 3 4 5 6 ...