做hacker.org上面的题目时,遇到了一个题目需要对RFC3280种长度为9的单词进行计数,并找出这些单词中出现次数最多的那个:Didactic Byte

RFC3280文档有7000多行,靠人工是数不出来的,解决这种是就得编程了,而且很明显,在处理此类问题时脚本式比较方便的,果断选择python

先是将题意理解错了,理解为出现次数最多的九个字母, 然后等到程序运行好提交答案时才发现不对,唉,真是汗颜

既然程序写出来了,还是将其贴出来吧

文档中字母频率计数:

 # find the occurence of single  letter from a document
#import fileinput test = ""
dicts = {} # read content from a document
# we could use readline,readlines etc.
# also we could use fileinput.input(filename) text = open('RFC3280.txt')
for line in text.readlines():
test += line.lower().replace(" ","") # use dictionary to store the occurence and it's letter
for i in xrange(97,123):
letter = chr(i)
count = test.count(chr(i))
#print "the accounts of %c is %d " % (letter,count)
dicts.setdefault(letter,count) # sort the dict by values,here I used a lambda expression
# to sort by keys:
# sorted_dict = sorted(dicts.iteritems(),key = lambda d:d[0]) sorted_dict = sorted(dicts.iteritems(),key = lambda d:d[1],reverse = True)
print sorted_dict

代码挺短的,注释也很详细,可以看出来脚本语言在处理这种事情上确实是比较方便

下面再看看,从文档中获取指定长度的单词的出现频率,并对其进行排序

 # this script is used to find all 9-letter word from specific document
# after find them, pick the most commom one from them
# as I used dictionary to store them, I can not output the one I want seperately
# the dictionary object is difference from list or an array,it store it's key:value rondomly test = ""
storage = []
dicts = {}
word_length = 9 # read content from a document
# as python script read lines from the document,it may contains '\n'
# at the end of a sentence,there followed a '.',we also need a handle with tring.replace function text = open('RFC3280.txt')
for line in text.readlines():
test += line.lower().replace('\n','').replace('.','') # convert a string to a list
lists = test.split(' ') # choose theses words which it's length is word_length,here is 9
for i in xrange(0,len(lists)):
if len(lists[i])==word_length:
storage.append(lists[i]) #print storage
#print len(storage) # now use dictionary.setdefault to add elements to dictionary
for n in xrange(0,len(storage)):
word = storage[n]
count = storage.count(word)
dicts.setdefault(word,count) # sort the dictionary order by vaules
sorted_dict = sorted(dicts.iteritems(),key = lambda d:d[1],reverse = True)
print sorted_dict

两段代码,实现的思路上差不多,都是从文件读取内容存入一个字符串中,这里是按行读取,所以要对字符串拼接。存入字符串后还需要进行一下处理,因为原文文本中有大量

的空格、换行符,其次句末的'.'也会被当作单词的一部分,还好这里要处理的符号不多,不然恐怕就要劳驾正则表达式了。然后将其转换为list(列表)对象,list有count属性可

直接对元素计数。由于需要知道每个元素出现的次数,我是用dictionary(字典)对象存储“键=>值”对,这里使用setdefault属性进行元素添加。注意到代码中使用了lambda

表达式,如果对lambda表达式不太熟悉建议还是查阅一下资料,遗憾的是一段时间没用python,我对这些知识点也没太大映像了,手头也没用相应资料(manual很好,有时候想查到某个比较细小的东西时会不太方便, 如果有安装bpython可能会方便很多),可参考:

使用 lambda 函数

细品lambda函数

python:lambda function

官方文档:内建类型

python字典的应用

dict、list、string常用用法

上面两段代码可以得出想要的结果,但在阅读体验上一大堆字典元素打印在一起还是需要改进的,今后会对其进行整理。

最后在贴上部分测试文件的内容,这里直接读取文件是因为python脚本和该文本文件处于同一目录下

  This memo profiles the X.509 v3 certificate and X.509 v2 Certificate
Revocation List (CRL) for use in the Internet. An overview of this
approach and model are provided as an introduction. The X.509 v3
certificate format is described in detail, with additional
information regarding the format and semantics of Internet name
forms. Standard certificate extensions are described and two
Internet-specific extensions are defined. A set of required
certificate extensions is specified. The X.509 v2 CRL format is
described in detail, and required extensions are defined. An
algorithm for X.509 certification path validation is described. An
ASN.1 module and examples are provided in the appendices.

使用Python对文档单词进行计数的更多相关文章

  1. python统计文档中词频

    python统计文档中词频的小程序 python版本2.7 效果如下: 程序如下,测试文件与完整程序在我的github中 #统计空格数与单词数 本函数只返回了空格数 需要的可以自己返回多个值 def ...

  2. 如何在命令行模式下查看Python帮助文档---dir、help、__doc__

    如何在命令行模式下查看Python帮助文档---dir.help.__doc__ 1.dir函数式可以查看对象的属性,使用方法很简单,举str类型为例,在Python命令窗口输入 dir(str) 即 ...

  3. 在命令行模式下查看Python帮助文档---dir、help、__doc__

    在命令行模式下查看Python帮助文档---dir.help.__doc__   1.dir函数式可以查看对象的属性,使用方法很简单,举str类型为例,在Python命令窗口输入 dir(str) 即 ...

  4. Python帮助文档中Iteration iterator iterable 的理解

    iteration这个单词,是循环,迭代的意思.也就是说,一次又一次地重复做某件事,叫做iteration.所以很多语言里面,循环的循环变量叫i,就是因为这个iteration. iteration指 ...

  5. sphinx:python项目文档自动生成

    Sphinx: 发音: DJ音标发音: [sfiŋks] KK音标发音: [sfɪŋks] 单词本身释义: an ancient imaginary creature with a lion's bo ...

  6. 三言两语聊Python模块–文档测试模块doctest

    doctest是属于测试模块里的一种,对注释文档里的示例进行检测. 给出一个例子: splitter.pydef split(line, types=None, delimiter=None): &q ...

  7. python 本地文档查看

    本地安装Python文档本地查看,在命令行中运行: python -m pydoc -p 1234 在浏览器中访问如下链接,就可以访问到本地文档: http://localhost:1234/ 本地文 ...

  8. 使用Sphinx生成本地的Python帮助文档

    第一步:安装Sphinx 首先我们需要安装Sphinx,如果已经安装了Anaconda,那么只需要使用如下命令即可安装,关于其中的参数 -c anaconda,可以在链接[1]中查看: conda i ...

  9. Python asyncio文档阅读摘要

    文档地址:https://docs.python.org/3/library/asyncio.html 文档第一句话说得很明白,asyncio是单线程并发,这种event loop架构是很多新型异步并 ...

随机推荐

  1. CSS3 过渡特性创建信封效果的联系表单

    最近给大家分享 CSS3 效果比较多,都是充分运用了 CSS3 来实现的.通过 CSS3 的新特性,我们创作出好的交互和效果的可能性大大增加.这篇文章中,我想与大家分享使用 CSS3 过渡特性实现的信 ...

  2. JS网页顶部弹出可关闭广告图层

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  3. kafka设计原理介绍

    背景介绍 Kafka简介 Kafka是一种分布式的,基于发布/订阅的消息系统.主要设计目标如下: 以时间复杂度为O(1)的方式提供消息持久化能力,即使对TB级以上数据也能保证常数时间的访问性能 高吞吐 ...

  4. iOS宏定义的使用与规范

    宏定义在很多方面都会使用,例如定义高度.判断iOS系统.工具类,还有诸如文件路径.服务端api接口文档.为了对宏能够快速定位和了解其功能,我们最好在定义的时候将其放入特定的头文件中 定义尺寸类的宏 D ...

  5. Maven提高篇系列之(四)——使用Profile

    这是一个Maven提高篇的系列,包含有以下文章: Maven提高篇系列之(一)——多模块 vs 继承 Maven提高篇系列之(二)——配置Plugin到某个Phase(以Selenium集成测试为例) ...

  6. 【C#】使用IExtenderProvider为控件添加扩展属性,像ToolTip那样

    申明: - 本文适用于WinForm开发 - 文中的“控件”一词是广义上的说法,泛指包括ToolStripItem.MenuItem在内单个界面元素,并不特指继承自Control类的狭义控件 用过To ...

  7. Firemonkey TComboBox 下拉菜单字型修改方法 (D10)

    在 FMX 下的 TComboBox 下拉菜单字型修改有二种方法: uses FMX.Pickers; 使用 Style,需先设定好 Style 后,再指定预设项的 Style,方法如下: proce ...

  8. Java并发编程:进程和线程之由来

    Java多线程基础:进程和线程之由来 在前面,已经介绍了Java的基础知识,现在我们来讨论一点稍微难一点的问题:Java并发编程.当然,Java并发编程涉及到很多方面的内容,不是一朝一夕就能够融会贯通 ...

  9. 点我吧工作总结(技术篇) zookeeper

    我思故我在,提问启迪思考! 1.什么是zookeeper? 2.zookeeper与dubbo.springMVC之间的协同工作? http://doc.okbase.net/congcong68/a ...

  10. Scalaz(20)-Monad: Validation-Applicative版本的Either

    scalaz还提供了个type class叫Validation.乍看起来跟\/没什么分别.实际上这个Validation是在\/的基础上增加了Applicative功能,就是实现了ap函数.通过Ap ...