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

  • 列表实例:由字符串创建一个作业评分列表,做增删改查询统计遍历操作。例如,查询第一个3分的下标,统计1分的同学有多少个,3分的同学有多少个等。
score=list('21223113321')
print('作业评分列表:',score)
score.append('3')
print('增加:',score)
score.pop()
print('删除:',score)
score.insert(2,'1')
print('插入:',score)
score[2]='2'
print('修改:',score)
print('第一个3分的下标:',score.index('3'))
print('1分的个数:',score.count('1'))
print('3分的个数:',score.count('3'))

  • 字典实例:建立学生学号成绩字典,做增删改查遍历操作。
d={'张三':93,'李四':74,'王五':45,'刘六':66}
print('学生成绩字典:',d)
d['钱二']=92
print('增加:',d)
d.pop('刘六')
print('删除:',d)
d['张三']=73
print('修改:',d)
print('查询李四成绩:',d.get('李四',''))

  • 列表,元组,字典,集合的遍历。
ls=list("4613125646")
tu=tuple("4613125646")
s=set("4613125646")
d={'张三':93,'李四':74,'王五':45,'刘六':66}
print("列表:",ls)
for i in ls:
    print(i,end=' ')
print("\n")
print("元组:",tu)
for i in tu:
    print(i,end=' ')
print("\n")
print("集合:",s)
for i in s:
    print(i,end=' ')
print("\n")
print("字典:",d)
for i in d:
    print(i,end='\t')
    print(d[i],end='\n')

  • 总结列表,元组,字典,集合的联系与区别。

  列表:有序,可做增删改查操作,用方括号[x,y,z]的方式表示

  元组:有序,不可做修改操作,用小括号(x,y,z)的方式表示

  字典:无序,可做增删改查操作,其中组成元素为键值对,用花括号{a:b,c:d}的方式表示

  集合:无序,可由列表创建,其中元素不重复,用花括号{x,y,z}的方式表示

 

  • 英文词频统计实例
    • 待分析字符串
    • 分解提取单词
      • 大小写 txt.lower()
      • 分隔符'.,:;?!-_’
    • 计数字典
    • 排序list.sort()
    • 输出TOP(10)
faded = '''You were the shadow to my light
Did you feel us?
Another start
You fade away
Afraid our aim is out of sight
Wanna see us
Alive
Where are you now?
Where are you now?
Where are you now?
Was it all in my fantasy?
Where are you now?
Were you only imaginary?
Where are you now?
Atlantis
Under the sea
Under the sea
Where are you now?
Another dream
The monster's running wild inside of me
I'm faded
I'm faded
So lost, I'm faded
I'm faded
So lost, I'm faded
These shallow waters never met what I needed
I'm letting go a deeper dive
Eternal silence of the sea. I'm breathing alive
Where are you now?
Where are you now?
Under the bright but faded lights
You've set my heart on fire
Where are you now?
Where are you now?
Where are you now?
Atlantis
Under the sea
Under the sea
Where are you now?
Another dream
The monster's running wild inside of me
I'm faded
I'm faded
So lost, I'm faded
I'm faded
So lost, I'm faded'''

faded = faded.lower()
for i in '?!,.\'\n':
    faded = faded.replace(i,' ')
words = faded.split(' ')

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

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

for i in range(10):
    print(c[i])

 

posted @ 2017-09-20 17:42  12-张振勋  阅读(308)  评论(0编辑  收藏  举报