【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学好?兴趣,兴趣,兴趣!找到你自己感兴趣的点进行切入,并找到兴趣点进行自我驱动是最好的学习方式! 推荐两本书,一本作为 ...
随机推荐
- PHP CLI下接受参数的几种方法
PHP CLI(命令行模式下)接受参数有多种方法: (1)使用$argv接受参数 <?php //变量仅在 register_argc_argv 打开时可用. print_r($argc); / ...
- [译]ASP.NET 5: New configuration files and containers
原文:http://gunnarpeipman.com/2014/11/asp-net-5-new-configuration-files-and-containers/ ASP.NET vNext提 ...
- php防注入
引发 SQL 注入攻击的主要原因,是因为以下两点原因: 1. php 配置文件 php.ini 中的 magic_quotes_gpc选项没有打开,被置为 off 2. 开发者没有对数据类型进行检查和 ...
- firstchild.data与childNodes[0].nodeValue意思(转)
x.firstchild.data:获取元素第一个子节点的数据: x.childNodes[0]::获取元素第一个子节点; x.childNodes[0].nodeValue.:也是获取元素第一个子节 ...
- Code First05--CodeFirst中值对象
今天主要介绍EF Code First中一个高级部分:Value Object,中文翻译过来叫做值对象. 所谓的值对象就是一些没有生命周期,也没有业务逻辑上唯一标识符的类.哪些类是Entity,哪些类 ...
- HDU 5592
原题: http://acm.hdu.edu.cn/showproblem.php?pid=5592 线段树的变形,先说思路. 题目中给出了当前节点之前的逆序对数,则p[i]-p[i-1]就是对于p[ ...
- linux安装包地址备忘
64位系统安装包: http://mirrors.163.com/centos/5/os/x86_64/CentOS/ 32位系统安装包: http://mirrors.163.com/centos/ ...
- NOSQL的学习
NoSQL(NoSQL = Not Only SQL ),意即"不仅仅是SQL",指的是非关系型的数据库.NoSQL用于超大规模数据的存储.(例如谷歌或Facebook每天为他们的 ...
- 在framework中打包xib
废话不多说,直接上图 1.Copy Bundle Resources 中加入相关xib 2.这里是重点,调用的时候不能直接写 [[NSBundle mainBundle] loadNibNamed:@ ...
- leetcode 215. Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the so ...