您的位置:首页 > 编程语言 > Python开发

python字典用法-统计统计一句单词

2017-03-01 14:25 246 查看
统计系统内存,然后查看到占用了多少百分比。
字符串的方法:
a.startswith() 返回的是一个bool(布尔)值。
a.split() 切分空格和制表符,然后返回的是一个列表。

#!/usr/bin/python
#coding:utf8

with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'):
total = int(line.split()[1])
continue
if line.startswith('MemFree'):
free = int(line.split()[1])
print "%.2f" %(free/1024.0)+'M'

#!/usr/bin/env python
#coding:utf-8

content="who have touched their lives Love begins with a smile grows with a kiss and ends with a tear The brightest future will always be based on a forgotten past you can’t go on well in lifeuntil you let go of your past failures and heartaches"

# 将文本拼接成word:num的字典形式

#循环列表,并且将单词作为字典的key,每出现一次这个单词,key+1

result = {}
for s in content.split(" "):
if s in result:
result[s] +=1
else:
result[s] = 1
#print result

# 字典翻转拼接为num:word的字典
res = {}
for k,v in result.items():
res.setdefault(v,[])
res[v].append(k)
#print res

count = 0

f = open('tongji.html','a+')
f.write("<html><table style='border:solid 1px'>")
f.write("<th style='border:solid 1px'>次数</th><th style='border:solid 1px'>单词</th>")
while count < 4:
key = max(res.keys())
print "出现了%s次的单词:%s" % (key,res[key])
for word in res[key]:
f.write('<tr><td style="border:solid 1px">%s</td><td style="border:solid 1px">%s</td></tr>' % (key,word))
res.pop(key)
count = count +1
f.write("</table></html>")
f.close()

一.
get()获得给定键相关联的值
dict = {‘name’:‘lorine’,‘age’:‘25’}
dict.get(‘name’)返回name对应的键值lorine,如果此键不存在字典中,则会返回None;
dict.get('work',‘student’)如果对应的键'work'不在字典中,则会返回默认的‘student’

二.
setdefault()获得给定键相关联的值,并更新字典,还能在字典中不含有给定键的情况下设置相应的键值
dict = {‘name’:‘lorine’,‘age’:‘25’}

dict.setdefault('name')或者dict.setdefault('name','lili')都是返回name对应的值lorine;

dict.setdefault('work')此键值不存在,则更新字典添加此键和默认值dict
={‘name’:‘lorine’,‘age’:‘25’,‘work’:None};
dict.setdefault('work','student')则更新字典dict ={‘name’:‘lorine’,‘age’:‘25’,‘work’:'student'};

描述
Python 字典(Dictionary) setdefault() 函数和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。
语法
setdefault()方法语法:
点击(此处)折叠或打开

dict.setdefault(key, default=None)

参数
key -- 查找的键值。
default -- 键不存在时,设置的默认键值。

返回值
该方法没有任何返回值。
实例
以下实例展示了 setdefault()函数的使用方法:
点击(此处)折叠或打开

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}

print "Value : %s" % dict.setdefault('Age', None)
print "Value : %s" % dict.setdefault('Sex', None)
以上实例输出结果为:
点击(此处)折叠或打开

Value : 7
Value : None

Python读写字典,如果Key不在Dict里面,就会导致抛出KeyError,如果没有做异常处理,那么程序就会挂断,平时自己写来玩耍的程序,挂掉没事,改了再重新跑呗。但是,如果在公司,可能一个程序要跑几天,因为这种小bug挂掉,就要重新跑一遍,非常影响工作效率。所以,读字典时,一定要考虑到Key not in Dict里面的情况,可以选择做异常处理。

temp = {'a':1,'b':1,'c':1}
h = ['a','e','c','b']
for index in h:
try:
print temp[index]
except KeyError:
print "has no key"

运行结果:
1
has no key
1
1

当然异常处理太麻烦了,可以用get函数来读取字典

dict.get(key, default=None) 参数

key -- 这是要搜索在字典中的键。

default -- 这是要返回键不存在的的情况下默认值。

返回值

该方法返回一个给定键的值。如果键不可用,则返回默认值为None。

Python 字典(Dictionary) setdefault() 函数和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。

dict.setdefault(key, default=None)

参数

key -- 查找的键值。
default -- 键不存在时,设置的默认键值。
以下实例展示了 setdefault()函数的使用方法:

dict = {'Name': 'Zara', 'Age': 7}

print "Value : %s" % dict.setdefault('Age', None)
print "Value : %s" % dict.setdefault('Sex', None)

Value : 7
Value : None

girls =['alice','bernice','clarice']
letterGirls ={}

for girl in girls:
letterGirls.setdefault(girl[0],[]).append(girl)

print letterGirls

{'a': ['alice'], 'c': ['clarice'], 'b': ['bernice']}

总结:get是读取时,防止key不存在产生的异常,setdefault是写入时,防止key不存在时产生的异常

>>> a={}
>>> a['key']='123'
>>> print (a)
{'key': '123'}
>>> print (a.setdefault('key','456')) #显示a这个字典的'key'值的内容,因为字典有,所以不会去设置它
123

>>> print (a.setdefault('key1','456')) #显示a这个字典的'key1'值的内容,因为字典没有,所以设置为456了
456
>>> a
{'key1': '456', 'key': '123'}

python中sys.setdefaultencoding('utf-8')的作用

在python中,编码解码其实是不同编码系统间的转换,默认情况下,转换目标是Unicode,即编码unicode→str,解码str→unicode,其中str指的是字节流,

而str.decode是将字节流str按给定的解码方式解码,并转换成utf-8形式,

u.encode是将unicode类按给定的编码方式转换成字节流str。注意调用encode方法的是unicode对象,生成的是字节流;

调用decode方法的是str对象(字节流),生成的是unicode对象。

若str对象调用encode会默认先按系统默认编码方式decode成unicode对象再encode,忽视了中间默认的
decode往往导致报错。

比如有如下代码:

  #! /usr/bin/env python
  # -*- coding: utf-8 -*-
  s = '中文字符' # 这里的 str 是 str 类型的,而不是 unicode
  s.encode('gb2312')

这句代码将 s 重新编码为 gb2312 的格式,即进行 unicode -> str 的转换。因为 s 本身就是 str 类型的,因此

Python 会自动的先将 s 解码为 unicode ,然后再编码成 gb2312。因为解码是python自动进行的,我们没有指明解码方式,python 就会使用 sys.defaultencoding 指明的方式来解码。很多情况下
sys.defaultencoding为ANSCII,如果 s 不是这个类型就会出错。

  UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position
  0: ordinal not in range(128)

对于这种情况,我们有两种方法来改正错误:
1. 明确的指示出 s 的编码方式

  #! /usr/bin/env python
  # -*- coding: utf-8 -*-
  s = '中文字符'
  s.decode('utf-8').encode('gb2312')

2. 更改 sys.defaultencoding 为文件的编码方式

  #! /usr/bin/env python
  # -*- coding: utf-8 -*-
  import sys
  reload(sys) # Python2.5 初始化后删除了 sys.setdefaultencoding 方法,我们需要重新载入
  sys.setdefaultencoding('utf-8')

  str = '中文字符'
  str.encode('gb2312')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息