19講 字典型數(shù)據(jù)學(xué)習(xí)

{鍵值對(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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容