【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学好?兴趣,兴趣,兴趣!找到你自己感兴趣的点进行切入,并找到兴趣点进行自我驱动是最好的学习方式! 推荐两本书,一本作为 ...
随机推荐
- WCF--验证码实现...
未开始待续... 未完待续...
- 原生态js获取节点的方法
<input value="我是用id来获取值的" type="button" onclick="GetById()"/> &l ...
- UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence
混淆了 python2 里边的 str 和 unicode 数据类型. 1. 对需要 str->unicode 的代码,可以在前边写上 import sys reload(sys) sys.se ...
- maven项目如何使用jetty启动?
1.在pom.xml文件中插入下面的片段 <build> <plugins> <plugin> <groupId>org.eclipse.jetty&l ...
- Android学习笔记(十三)——广播机制
//此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! Android 中的每个应用程序都可以对自己感兴趣的广播进行注册,这样该程序就只会接收到自己所关心的广播内容 ...
- [POJ3096]Surprising Strings
[POJ3096]Surprising Strings 试题描述 The D-pairs of a string of letters are the ordered pairs of letters ...
- HTML 5 <input> placeholder 属性
原文链接:http://www.w3school.com.cn/html5/att_input_placeholder.asp HTML 5 <input> placeholder 属性 ...
- opencv图像操作
cvAbs 计算数组中所有元素的绝对值 cvAbsDiff 计算两个数组差值的绝对值 cvAbsDiffs 计算数组和标量差值的绝对值 cvAdd 两个数组的元素级的加运算 cvAdds 一个数组 ...
- BestCoder Round #86 解题报告
A.Price List Sol 求和查询 Code #include<cstdio> #include<algorithm> #include<iostream> ...
- 将Apache加入到linux系统service
将Apache加入到linux系统service 将apache加入到linux系统服务,用service命令来控制apache的启动和停止. 本文由乌合之众瞎写http://www.cnblogs. ...