组合数据类型练习,英文词频统计实例上
1.字典实例:建立学生学号成绩字典,做增删改查遍历操作。
#创建字典 d={'10':'90','20':'95','30':'89','40':'92','50':'88'} print(d) #增加 d['60']=97 print('增加一个学号为60的学生信息:',d) #查找 print('查找出学号50的学生成绩:',d['50']) #删除 d.pop('40') print('删除学号为40的学生信息:',d) #修改 d['10']=85 print('修改学号为10的学生成绩为85:',d) #遍历 print('遍历:') for i in d: print(i,d[i])
2.列表,元组,字典,集合的遍历。
ls=list('52548232130') print(ls) for i in ls: print(i) tu=tuple('52548232130') print(tu) for i in tu: print(i) se=set('52548232130') print(se) for i in se: print(i) d={'201506050060':1,'20150605061':2,'201506050062':3,'201506050063':4} print(d) for i in d: print(i,d[i])
总结列表,元组,字典,集合的联系与区别。
列表,元组,字典,集合的联系与区别:列表,元组是有顺序的,而字典和集合是没顺序的。列表是以[ ]形式表示,元组是以( )表示,字典以{ }表示,集合则是以[()]的形式表示。列表是可变对象,可以有增删改操作,而元组是只读的,不能修改。字典使用键-值(key-value)存储,键是不可变的对象。插入和查找速度快,不会随着键的增加而变慢,需要占用大量的内存。字典是用空间换取时间的一种方法。集合是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素。
3.英文词频统计实例
1.待分析字符串
2.分解提取单词
1.大小写 txt.lower()
2.分隔符'.,:;?!-_’
3. 单词列表
3.单词计数字典
news='''Come up to meet you, tell you I'm sorry You don't know how lovely you are I had to find you Tell you I need you Tell you I set you apart Tell me your secrets Ask me your questions Oh, let's go back to the start Running in circles Coming up tales Heads on a science apart Nobody said it was easy It's such a shame for us to part Nobodysaid it was easyNo one ever said it would be this hard Oh, take me back to the start I was just guessing At numbers and figures Pulling your puzzles apart Questions of science Science and progress Do not speak as loud as my heart Tell me you love me Come back and haunt me Oh, and I rush to the start Running in circles Chasing tales Coming back as we are Nobody said it was easy Oh, it's such a shame for us to part Nobody said it was easyNo one ever said it would be so hard I'm going back to the start.''' #将所有大写转换为小写 news=news.lower() print('转换为小写的结果:'+news+'\n') #将所有分隔符'.,:;?!-_’替换为空格 for i in '.,:;?!-_': news=news.replace(i,' ') print('其他分隔符替换为空格的结果:'+news+'\n') #分隔出一个一个单词 news=news.split(' ') print('分隔结果为:',news,'\n') #单词计数字典 word=set(news) dic={} for i in word: dic[i]=news.count(i) news=list(dic.items()) news.sort(key=lambda x:x[1],reverse=True) print('单词计数字典结果为:',news,'\n')