【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学好?兴趣,兴趣,兴趣!找到你自己感兴趣的点进行切入,并找到兴趣点进行自我驱动是最好的学习方式! 推荐两本书,一本作为 ...
随机推荐
- Linux下运行C语言程序
一.编写C语言的源代码 二.用gcc -c C文件名生成.o文件 三.用gcc -o 可执行文件名 .o文件名 生成可执行文件 四.输入可执行文件名前加./执行可执行文件
- Mac os装软件时提示显示需要安装旧Java SE 6运行环境解决办法
这个时Java版本的问题,换用合适的低版本即可,下面是官方的 https://support.apple.com/kb/DL1572?viewlocale=zh_CN&locale=en_US ...
- NoSuchMethodException问题总结
1.编译异常,这个很容易发现并解决: method真的没有 替换jar包没有clean project. 2.编译正常,运行报错 这是一个遇到之后让人纳闷的异常,脑袋不转弯的时候真的容易被卡住.这时只 ...
- JQuery实战图片特效-遁地龙卷风
(-1)写在前面 这个idea是我拷贝别人的,但代码是我自已一点点敲出来的,首先向这位前辈致敬,我用的是chrome49.firefox43.IE9,jquery3.0.言辞请结合代码,避免断章取意. ...
- jQuery对话框插件 ThickBox
http://baike.haosou.com/doc/7607201-7881296.html 项目已经停止维护,但该插件还是不错的! ThickBox是一个基于JQuery类库的扩展,它能在浏览器 ...
- [转]CentOS 5.3通过yum升级php到最新版本的方法
来自:www.jasonlitka.com/media 通过测试,方法三可行: 方法三 vim /etc/yum.repos.d/utterramblings.repo 输入 [utterrambli ...
- Java 7 Concurrency Cookbook 翻译 第一章 线程管理之四
七.创建和运行一个后台线程 Java中有一种特别的线程叫做 deamon(后台) 线程.这类线程具有非常低的权限,并且只有在同一个程序中没有其他的正常线程在运行时才会运行.注意:当一个程序中只剩下后台 ...
- [codevs1001]舒适的路线
[codevs1001]舒适的路线 试题描述 Z小镇是一个景色宜人的地方,吸引来自各地的观光客来此旅游观光.Z小镇附近共有N(1<N≤500)个景点(编号为1,2,3,-,N),这些景点被M(0 ...
- 多通道(Multichannel)单通道(singlechannel)图像概念梳理
在做机器视觉时,常常要将一个多通道图像分离成几个单通道图像或者将几个单通道图像合成一个多通道图像,以方便图像处理,但是.写这篇博客,是为加深对这两个概念的理解,下面会给出部分OpenCV对单通道与多通 ...
- Android活动的生命周期
掌握活动的生命周期对任何Android开发者来说都非常重要,当你深入理解活动的生命周期之后,就可以写出更加连贯流畅的程序. -------------------------------------- ...