43张正杰

导航

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

1、列表实例:由字符串创建一个作业评分列表,做增删改查询统计遍历操作。例如,查询第一个3分的下标,统计1分的同学有多少个,3分的同学有多少个等。

score = list('012332211')
print('分数为:',score)
print('1分的同学个数:',score.count('1'))
print('3分的同学个数:',score.count('3'))
print('第一个3分同学的下标为:',score.index('3'))
score.append('0')
print('添加一个0分在表的末尾:',score)
score.insert(0,'3')
print('添加一个3分在表的开头:',score)
score.pop(1)
print('删除第二个分数:',score)

 

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

 1 score = {'01':'100','02':'77','03':'88','04':'97','05':'97','05':'96','06':'60','07':'55','08':'90','09':'91','10':'59'}
 2 print('成绩表:\n',score.items())
 3 score['11']='90'
 4 print('添加学号为11的分数:\n',score.items())
 5 score['10']='99'
 6 print('修改学号为10的分数为99分:\n',score.items())
 7 print('学号是:',score.keys())
 8 print('分数是:',score.values())
 9 found = input('输入学号查分数:')
10 print(score.get(found,"没有该学生的分数!"))

 

 3、分别做列表,元组,字典,集合的遍历,并总结列表,元组,字典,集合的联系与区别。

 1 ls = list('123456789')
 2 ln = tuple('123456789')
 3 s = {'01':'100','02':'99','03':'98','04':'97','05':'96','05':'96','06':'95','07':'98','08':'90','09':'91'}
 4 a= set('123456789')
 5 print('列表:',ls)
 6 print('元组',ln)
 7 print('字典',s)
 8 print('集合',a)
 9 print('\n列表的遍历:')
10 for i in ls:
11     print(i,' ',end='  ')
12 print('\n元组的遍历:')
13 for j in ln:
14     print(j,' ',end='  ')
15 print('\n字典的遍历:')    
16 for k in s:
17     print(k,'',end='  ')
18 print('\n集合的遍历:')    
19 for l in a:
20     print(l,'',end='  ')

 

4、英文词频统计实例

过程:待分析字符→分解提取单词→大小写 txt.lower()→分隔符'.,:;?!-_’ →计数字典→排序list.sort()→输出TOP(10)。

write='''It was Mother’s Day.Sun Zheng thought he should do something for his mother.
He decided to help his mother do some housework.After school he went to a shop to buy some food on his way home.
When he got home,he did his best to cook some nice food,though he couldn’t do the cooking well.
Then he cleaned the room.He felt very tired,but he was very happy.
When his father and his mother came back and saw the clean rooms and dishes which weren’t so nice,they were very happy.
They had their supper together.His mother said,"Thank you,my child!"'''

exc={'the','to','and','on','a','was'}
write = write.lower()
for i in ''',.!?''':   #去掉标点符号
    write = write.replace(i,' ')
words = write.split(' ')  #分词,单词的列表
keys = set(words)  #出现过单词的集合,字典的Key
dic = {}
for w in exc:   #排除无意义的单词
    keys.remove(w)
for i in keys:
    dic[i]=words.count(i)  #单词出现次数的字典
diry = list(dic.items())  #把字典转换为列表
diry.sort(key = lambda x:x[1],reverse = True)  #按出现的次数降序排序
for i in range(10):
    print(diry[i])

 

posted on 2017-09-21 19:57  43张正杰  阅读(154)  评论(0编辑  收藏  举报