组合数据类型练习,英文词频统计实例上

建立学生学号成绩字典,做增删改查遍历操作。

>>> d={'Michael':95,'Bob':75,'Tracy':85}
>>> d.get('Bob')
75
>>> d.pop('Bob') 
75
>>> d
{'Michael': 95, 'Tracy': 85}
>>> d.values()
dict_values([95, 85])
>>> d.keys()
dict_keys(['Michael', 'Tracy'])
>>> d.items()
dict_items([('Michael', 95), ('Tracy', 85)])
>>> d1={'Bobi':100}
>>> d.update(d1)
>>> d
{'Michael': 95, 'Tracy': 85, 'Bobi': 100}
>>> d['Tracy']=90
>>> d
{'Michael': 95, 'Tracy': 90, 'Bobi': 100}

 

列表元组字典集合的遍历

>>> ls=list('123456789')
>>> tu=tuple('abcdefgfh')
>>> ls
['1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> tu
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'f', 'h')
>>> d=dict(zip(tu,ls))
>>> d
{'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5', 'f': '8', 'g': '7', 'h': '9'}
>>> for i in ls:
    print(i)

    
1
2
3
4
5
6
7
8
9
>>> for i in tu:
    print(i)

    
a
b
c
d
e
f
g
f
h
>>> for i in d:
    print(i,d[i])

    
a 1
b 2
c 3
d 4
e 5
f 8
g 7
h 9
>>> ss=set('123321456')
>>> ss
{'4', '1', '3', '5', '6', '2'}
>>> for i in ss:
    print(i)

    
4
1
3
5
6
2
>>> 

 

总结列表,元组,字典,集合的联系与区别。

(1)列表用方括号表示,随时可以增删查改。

(2)元组用圆括号表示。元组和列表的大部分操作相同。不同于元组初始后就不能更改。

(3)与列表和元组不同,集合是无序的,也不能通过索引进行访问。集合中的元素不能重复。

(4)字典用大括号表示。与集合相比,通过关键字索引,所以比集合访问更快。可用ls与tu

映射而成。

英文词频统计实例

  1. 待分析字符串
  2. 分解提取单词
    1. 大小写 txt.lower()
    2. 分隔符'.,:;?!-_’
    3. 单词列表
  3. 单词计数字典

word='''Failure is probably the fortification in your pole.
It is like a peek your wallet as the thief,when you are thinking how to spend several hard-won lepta,when you are wondering whether new money,it has laid background.
Because of you,then at the heart of the most lax,alert,and most low awareness,and left it godsend failed.'''
word=word.lower()
for i in ',.':
    word=word.replace(i,' ')
words=word.split(' ')
print(words)
s=set(words)
d={ }
for i in words:
    d[i]=words.count(i)
for i in d:
    print('{0:<20}{1:>3}'.format(i,d[i]))

 

posted @ 2017-09-22 12:50  003刘淑千  阅读(150)  评论(0编辑  收藏  举报