19讲 字典型数据学习

{键值对}

>>> 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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容