{键值对}
>>> d={"201801":"小明","201802":"小红","201803":"小白"}
>>> print(d["201802"])
小红
>>> d["201802"]="小绿"
>>> print(d)
{'201802': '小绿', '201803': '小白', '201801': '小明'}
>>> a={"01":"张三","02":"李四"}
>>> type(a)
<class 'dict'> #字典型
>>> a["02"]="李五"
>>> a
{'01': '张三', '02': '李五'}
>>> a.keys()
dict_keys(['01', '02'])
>>> a.values()
dict_values(['张三', '李五'])
>>> a.get("02")
'李五'
文本词频统计
# CalHamlet.py
def getText():
txt = open("hamlet.txt", "r").read()
txt = txt.lower()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(ch, " ") #将文本中特殊字符替换为空格
return txt
hamletTxt = getText()
words = hamletTxt.split()
counts = {}
for word in words:
counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(10):
word, count = items[i]
print ("{0:<10}{1:>5}".format(word, count))
=============== RESTART: F:\Python2\行文代码\行文代码\第6章\CalHamlet.py ===============
the 1138
and 965
to 754
of 669
you 550
a 542
i 542
my 514
hamlet 462
in 436