组合数据类型练习,英文词频统计实例上
1.字典实例:建立学生学号成绩字典,做增删改查遍历操作。
dic={} dic['001']='80' dic['002']='88' dic['003']='79' dic['004']='82' dic['005']='76' dic['006']='91' print('学生学号成绩字典:',dic) dic['007']='96' print('做增加操作后的字典:',dic) dic.pop('004','82') print('做删除操作后的字典:',dic) dic['001']='90' print('做修改操作后的字典:',dic) print('学号006同学的成绩为:',dic['006']) print('对字典进行遍历:') for i in dic: print(i,dic[i])

2.列表,元组,字典,集合的遍历。
总结列表,元组,字典,集合的联系与区别。
li=list('12648896354') print('列表:',li) print('列表遍历:') for i in li: print(i) tu=tuple('12648896354') print('元组::',tu) print('元组遍历:') for i in tu: print(i) d={'001':90,'002':88,'003':79,'004':82,'005':76} print('字典:',d) print('字典遍历:') for i in d: print(i,d[i]) s=set('2233311323') print('集合:',s) print('集合遍历:') for i in s: print(i)

元组:可以包含不同类型的对象,但是是不可变的,不可以在增减元素,用()来定义.
列表:列表是Python中最具灵活性的有序集合对象类型,与字符串不同的是,列表可以包含任何种类的对象:数字,字符串,甚至是其他列表.并且列表都是可变对象,它支持在原处修改的操作.也可以通过指定的索引和分片获取元素.列表就是元组的可变版本,用[]来定义.
字典:字典(Dictionary) 是 Python 的内置数据类型之一,它定义了键和值之间一对一的关系,但它们是以无序的方式储存的。
定义 Dictionary 使用一对大(花)括号” { } ”。
集合:Python的集合(set)和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算.由于集合是无序的,所以,sets 不支持 索引, 分片, 或其它类序列(sequence-like)的操作。
3.英文词频统计实例
- 待分析字符串
- 分解提取单词
- 大小写 txt.lower()
- 分隔符'.,:;?!-_’
- 单词列表
- 单词计数字典
s='''We were born from light before there even was a dawn So pure so bright Falling from the skies above into our darkened fate The time has come Walking through this world we know the secret of our lives The light we share Caught in destiny we shine for we are meant to be The star guardians Gone in a flash before our time Up in the skies together The vow we have made has kept us strong Don't fade away it's time to shine Burning bright As we reach out for the same horizon Burning brighter We're running outta time we're chasing the light Gone in a flash before our time Up in the skies together The vow we have made has kept us strong Don't fade away it's time to shine Burning bright As we reach out for the same horizon Burning brighter Piercing through the dawn dark we burn on and on and on The sight stuck in my mind I long for the days we were young The sound in my heart Light in your eyes But now I drown in tears I cry Yelling your name into the rain Don't push me away let's head for the sky Gone in a flash before our time Up in the skies together The vow we have made has kept us strong Don't fade away it's time to shine Burning bright As we reach out for the same horizon Burning brighter Running outta time we're chasing the light Burning bright As we reach out for the same horizon Burning brighter Piercing through the dawn we burn on and on and on ''' r=s.lower() for i in ',.?!': r=r.replace(i,' ') r=r.split(' ') print(r) word=set(r) dic={} for i in word: dic[i]=r.count(i) r=list(dic.items()) r.sort(key=lambda x:x[1],reverse=True) print(r,'\n') print('词频前十为:') for i in range(10): word,count=r[i] print('{0}={1}'.format(word,count))

浙公网安备 33010602011771号