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

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

2.列表,元组,字典,集合的遍历。

a=list('1357')
print('遍历列表:')
for i in a:
    print(i)
    
b=tuple('2468')
print('遍历元组:')
for i in b:
    print(i)
    
c={'01':88,'02':96,'03':91}
print('遍历字典:')
for i in c:
    print(i,c[i])
    
d=set(a)
print('遍历集合:')
for i in d:
    print(i)

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

答:(1)列表是任意对象的序列。列表用方括号表示。

       (2)将一组值打包到一个对象中,称为元组。元组用圆括号表示。元组和列表的大部分操作相同。但是,列表是不固定的,可以随时插入,删除;而元组一旦确认就不能够再更改。所以,系统为了列表的灵活性,就需要牺牲掉一些内存;而元组就更为紧凑。(注意,元组在定义过程中,字符串必须用单引号‘扩起来。)

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

       (4)字典就是一个关联数组或散列表,其中包含通过关键字索引的对象。用大括号表示。与集合相比,通过关键字索引,所以比集合访问方便。字典是Python解释器中最完善的数据类型。

3.英文词频统计实例

A.待分析字符串

B.分解提取单词

   a.大小写 txt.lower()

   b.分隔符'.,:;?!-_’

   c.单词列表

C.单词计数字典

song='''I messed up tonight, I lost another fight
I still mess up but I'll just start again
I keep falling down, I keep on hitting the ground
I always get up now to see what's next
Birds don't just fly, they fall down and get up
Nobody learns without getting it won
I won't give up, no I won't give in
Til I reach the end, then I'll start again
No I won't leave, I wanna try everything
I wanna try even though I could fail
I won't give up, no I won't give in
Til I reach the end and then I'll start again
No I won't leave, I wanna try everything
I wanna try even though I could fail'''
song=song.lower()
for i in ',':
    song=song.replace(i,' ')
words=song.split(' ')
print(words)
dict={}
for i in words:
    dict[i]=words.count(i)
print(dict)

posted @ 2017-09-22 17:26  004熊锋阳  阅读(135)  评论(0编辑  收藏  举报