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

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

score = list('222331132')
print('分数为:'),score
print('得1分的同学个数:'),score.count('1')
print('得3分的同学个数:'),score.count('3')
print('第一个3分同学的下标为:'),score.index('3')
score.append('0')

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

>>> d={'09':'66','05':'80','14':'78','23':'90'}
>>> d['23']
'90'
>>> d.keys()
dict_keys(['09', '05', '14', '23'])
>>> d.values()
dict_values(['66', '80', '78', '90'])
>>> d.items()
dict_items([('09', '66'), ('05', '80'), ('14', '78'), ('23', '90')])
>>> d.get('05')
'80'
>>> print(d.get('01','00'))
>>> d
{'09': '66', '05': '80', '14': '78', '23': '90'}
>>> d['01']='11'
>>> d
{'09': '66', '05': '80', '14': '78', '23': '90', '01': '11'}
>>> del(d['01'])
>>> d
{'09': '66', '05': '80', '14': '78', '23': '90'}

3、列表,元组,字典,集合的遍历。

l=list('1101010101')
t=tuple('1101010101')
s=set('1101010101')
d=dict(zip('abcd',[1,2,3,4]))
print('列表',l)
for i in l:
    print(i,end=' ')
print('\n')
print('元组',t)
for i in t:
    print(i,end=' ')
print('\n')
print('集合',s)
for i in s:
    print(i,end=' ')
print('\n')
print('字典',d)
for i in d:
    print(i,d[i])

4、英文词频统计实例

f=open('E:/作业/2017课程考核/Python/red.txt')
songs=f.read()
f.close()

songs =songs.replace("\n",' ')
exc={'the','a','to','of','and','in','that','on'}
songs=songs.lower()
for i in ',…':
    songs=songs.replace(i,' ')

print(songs)

words=songs.split(' ')
keys=set(words)
for w in exc:
    keys.remove(w)

dic={}
for i in keys:
    dic[i]=words.count(i)

wc=list(dic.items())
wc.sort(key=lambda x:x[1],reverse=True)

for j in range(10):
    print(wc[j])

 

posted @ 2017-09-21 20:16  lesssharp  阅读(133)  评论(0编辑  收藏  举报