组合数据类型练习,英文词频统计实例上
字典实例:建立学生学号成绩字典,做增删改查遍历操作。
d={'张三':'01','山崎贤人':'02','王五':'03'}
d['张三']
d['张三']
'01'
>>> d.pop('张三')
'01'
>>> d.keys()
dict_keys(['山崎贤人', '王五'])
d['刘维']='04'
>>> d
{'山崎贤人': '02', '王五': '03', '刘维': '04'}
>>> d['刘维']='05'
>>> d
{'山崎贤人': '02', '王五': '03', '刘维': '05'}
2、列表,元组,字典,集合的遍历。
>>> ls=list('123456')
>>> tu=tuple('abceef')
>>> s=set(ls)
>>> s
{'2', '1', '3', '5', '6', '4'}
>>> for i in ls:
print(i)
1
2
3
4
5
6
>>> for i in tu:
print(i)
a
b
c
e
e
f
for i in s:
print(i)
2
1
3
5
6
4
>>> d=dict(zip(tu,ls))
>>> d
{'a': '1', 'b': '2', 'c': '3', 'e': '5', 'f': '6'}
>>> for i in d:
print(i,d[i])
a 1
b 2
c 3
e 5
f 6
总结列表,元组,字典,集合的联系与区别。
列表中的项目应该包括在方括号中,
你可以添加、删除或是搜索列表中的项目。
由于你可以增加或删除项目,所以列表是可变的数据类型,
即这种类型是可以被改变的。
元组和列表十分类似,但是元组是不可变的.
也就是说你不能修改元组。
元组通过圆括号中用逗号分割的项目定义。
元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,
即被使用的元组的值不会改变。
集合没有特殊的表示方法,而是通过一个set函数转换成集合。集合是一个无序不重复元素集,基本功能包括关系测试和消除重复元素.。
字典最大的价值是查询,通过键,查找值。
3、英文词频统计实例
a、待分析字符串
b、分解提取单词
- 大小写 txt.lower()
- 分隔符'.,:;?!-_’
- 单词列表
c、单词计数字典
Twinkle Twinkle Little Star (Declan's Prayer) - Declan Galbraith Twinkle twinkle little star, How I wonder what you are, Up above the world so high, Like a diamond in the sky, Star light, Star bright, The first star I see tonight, I wish I may, I wish I might, Have the wish I wish tonight, Twinkle twinkle little star, How I wonder what you are, I have so many wishes to make, But most of all is what I state, So just wonder, That I've been dreaming of, I wish that I can have owe her enough, I wish I may, I wish I might, Have the dream I dream tonight, Ooo baby song='''Twinkle Twinkle Little Star (Declan's Prayer) - Declan Galbraith Twinkle twinkle little star, How I wonder what you are, Up above the world so high, Like a diamond in the sky, Star light, Star bright, The first star I see tonight, I wish I may, I wish I might, Have the wish I wish tonight, Twinkle twinkle little star, How I wonder what you are, I have so many wishes to make, But most of all is what I state, So just wonder, That I've been dreaming of, I wish that I can have owe her enough, I wish I may, I wish I might, Have the dream I dream tonight, Ooo baby Twinkle twinkle little star, How I wonder what you are, I want a girl who'll be all mine, And wants to say that I'm her guy, Someone's sweet that's for sure, I want to be the one shes looking for, I wish I may, I wish I might, Have the girl I wish tonight, Ooo baby Twinkle twinkle little star, How I wonder what you are, Up above the world so high, Like a diamond in the sky, Star light, Star bright, The first star I see tonight, I wish I may, I wish I might, Have the wish I wish tonight.''' song=song.lower() for i in '''.,-\n\t\u3000'()"''': song=song.replace(i,'') words=song.split(' ') dic={} keys=set(words) for w in keys: dic[w]=words.count(w) for w in dic: print("{0:<10}{1}".format(w,dic[w]))