Python3实现统计单词表中每个字母出现频率的方法示例

yipeiwu_com5年前Python基础

本文实例讲述了Python3实现统计单词表中每个字母出现频率的方法。分享给大家供大家参考,具体如下:

作为python字典与数组概念的运用,统计字母表中每个字母出现的频率,作为练习再合适不过。

解决问题过程中需要用到的知识点包括:字典的创建、增添元素,数组的创建、增添元素,数组的遍历等

这个问题解决的思路为:首先从文件中按行依次读入单词,去除换行符后添加到数组 new_list 中。依次遍历数组 new_list 的每一个字符串,将每个字符串连同上一次循环中的频率统计结果 old_d (old_d在遍历new_list之前进行初始化)一起作为实参传递给频率统计函数 histogram()。histogram()函数在上一轮频率统计基础上得出本轮频率统计结果,结果通过字典 d 传回,将值赋给 old_d 。直到遍历完new_list,再将 old_d 统计结果打印。

'''transform string into dictionary
s is input string
d is dictionary to restore every bit in string
'''
def histogram(s, old_d):
  d = old_d
  for c in s:
    d[c] = d.get(c, 0) + 1
  return d
'''This function can calculate the frequency of every letter in alphabet
'''
fin = open("words.txt")
new_list = []
for line in fin:
  rs = line.rstrip('\n') #delete the '\n' after every letter
  new_list.append(rs) # new_list is used to restore letters
old_d = dict() # initialize the dictionary
for i in range(len(new_list)): #calculate the letter
#frequency of every word
  old_d = histogram(new_list[i], old_d) #old_d is used to
  #restore letter frequency before new_list[i]
print(old_d)

这里words.txt文档内容如下:

But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief

代码运行结果:

{'B': 1, 'u': 6, 't': 12, ' ': 29, 's': 11, 'o': 8, 'f': 3, 'w': 4, 'h': 9, 'a': 10, 'l': 6, 'i': 13, 'g': 3, 'r': 7, 'y': 2, 'n': 9, 'd': 6, 'e': 12, 'b': 1, 'k': 3, 'I': 1, 'J': 1, 'A': 1, 'v': 1, 'm': 1, 'W': 1, 'c': 1, 'p': 1}

PS:这里再为大家推荐2款相关统计工具供大家参考:

在线字数统计工具:
http://tools.jb51.net/code/zishutongji

在线字符统计与编辑工具:
http://tools.jb51.net/code/char_tongji

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

举例讲解Python中字典的合并值相加与异或对比

字典合并值相加 在统计汇总游戏数据的时候,有些数据是是每天用字典存的,当我要对多天汇总的时候,就需要合并字典了。 如果key相同的话它们的值就相加。 不能用update方法,因为用upd...

python字符串替换的2种方法

python 字符串替换 是python 操作字符串的时候经常会碰到的问题,这里简单介绍下字符串替换方法。 python 字符串替换可以用2种方法实现: 1是用字符串本身的方法。 2用正...

pygame实现成语填空游戏

pygame实现成语填空游戏

最近看到很多人玩成语填字游戏,那么先用pygame来做一个吧,花了大半天终于完成了,附下效果图。 偷了下懒程序没有拆分,所有程序写在一个文件里,主要代码如下: # -*- codi...

Django如何简单快速实现PUT、DELETE方法

使用django的小伙伴们应该都知道我们是无法开心的处理PUT跟DELETE的 $.ajax({ url: 'XXX', type: 'PUT', dataType: '...

tensorflow识别自己手写数字

tensorflow识别自己手写数字

tensorflow作为google开源的项目,现在赶超了caffe,好像成为最受欢迎的深度学习框架。确实在编写的时候更能感受到代码的真实存在,这点和caffe不同,caffe通过编写配...