Chinaunix首页 | 论坛 | 博客
  • 博客访问: 108896
  • 博文数量: 49
  • 博客积分: 2612
  • 博客等级: 少校
  • 技术积分: 431
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-01 14:31
个人简介

来来去去

文章分类

全部博文(49)

文章存档

2015年(1)

2012年(4)

2011年(1)

2010年(42)

2009年(1)

我的朋友

分类: Python/Ruby

2010-01-21 14:51:07

统计文章中各字符的总数:
  方法:
    1。读取文件。
    2。建立一个空字典。
    3。比较文件中的每一个字符,如果在字典中存在(dict1.has_key(s)),刚相应的值得加1。如果不存在则把这个字符添加到字典里去并赋值1。

setdefault 方法:
  

import os
import sys

if __name__=='__main__':

    f=open("E:\\pythonchallenge\\rare\\rare.txt","r")
    str=f.read()
    dict1={}

    for s in str:
        if dict1.has_key(s): # check wether the dict contain the key "s"
            dict1[s]+=1
        else: # added the key "s" and set the vaule to 1 if "s" not exist in dict.
            dict1.setdefault(s,1)
    f.close()

    for key,value in dict1.items():
        print key,":",value


阅读(986) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~