组合数据类型,英文词频统计
练习:
- 总结列表,元组,字典,集合的联系与区别。
- 列表,元组,字典,集合的遍历。
列表,元组,字典是有顺序的,而集合是没顺序的
列表是以方括号形式表示,元组是以圆括号表示,字典以花括号表示,集合则是以[()]的形式表示
列表是可变对象,它支持在原处修改的操作.也可以通过指定的索引和分片获取元素。区别于元组,可动态增加,删除,更新。
元组和列表在结构上没有什么区别,唯一的差异在于元组是只读的,不能修改。元组用“()”表示。元组一旦定义其长度和内容都是固定的。一旦创建元组,则这个元组就不能被修改,即不能对元组进行更新、增加、删除操作。若想创建包含一个元素的元组,则必须在该元素后面加逗号“,”,否则创建的不是一个元组,而是一个字符串。
集合没有特殊的表示方法,而是通过一个set函数转换成集合。集合是一个无序不重复元素集,基本功能包括关系测试和消除重复元素.。
字典最大的价值是查询,通过键,查找值。
英文词频统计:
- 下载一首英文的歌词或文章str
- 分隔出一个一个的单词 list
- 统计每个单词出现的次数 dict
strlrc = '''Need You Now - Lady Antebellum Picture perfect memories Scattered all around the floor Reaching for the phone cause I can't fight it any more And I wonder if I ever cross your mind For me it happens all the time It's a quarter after one I'm all alone and I need you now Said I wouldn't call but I lost all control and I need you now And I don't know how I can do without I just need you now Another shot of whiskey can't stop looking at the door Wishing you'd come sweeping in the way you did before And I wonder if I ever cross your mind For me it happens all the time It's a quarter after one I'm a little drunk And I need you now Said I wouldn't call but I lost all control and I need you now And I don't know how I can do without I just need you now Yes I'd rather hurt than feel nothing at all It's a quarter after one I'm all alone and I need you now And I said I wouldn't call but I'm a little drunk and I need you now And I don't know how I can do without I just need you now I just need you now Oh baby I need you now ''' strList = strlrc.split() strSet = set(strList) strDict = {} for word in strSet: strDict[word] = strList.count(word) print(len(strDict), strDict)