- 论坛徽章:
- 0
|
统计文章中各字符的总数:
方法:
1。读取文件。
2。建立一个空字典。
3。比较文件中的每一个字符,如果在字典中存在(dict1.has_key(s)),刚相应的值得加1。如果不存在则把这个字符添加到字典里去并赋值1。
setdefault 方法:
http://www.tutorialspoint.com/python/dictionary_setdefault.htm
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+=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
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/107101/showart_2156168.html |
|