{鍵值對(duì)}
>>> 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")
'李五'
文本詞頻統(tǒng)計(jì)
# 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