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

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

s={'001':65,'002':66,'003':88,'004':95,'005':85,'006':78}
print('添加007学生信息:')
s['007']=98
print(s.items())
print('删除006的记录:')
print(s.pop('006'))
print('将003的成绩改为99')
s['003']=99
print(s.items())
print('查询002的成绩:')
print(s['002'])
print("遍历:")
for i in s:
   print(i,s[i])

 

 

 

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

li=list('4564532798')
t=tuple('gshgfra')
s={'001':65,'002':66,'003':78,'004':88,'004':95,'006':78}
x=set(li)
print('列表的遍历为:')
for i in li:
   print(i)
print()
print('元祖的遍历为:')
for i in t:
   print(i)
print()
print('字典的遍历为:')
for i in s:
    print(i,s[i])
print()
print('集合的遍历为:')
for i in x:
    print(i)
print()

 


print('字典的遍历为:')
for i in s:
    print(i,s[i])
print()
print('集合的遍历为:')
for i in x:
    print(i)
print()

   

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

  1. 列表和元组是有序的,字典和集合都是无序的。
  2. 列表用“[]”表示。列表是可变对象,它支持在原处修改的操作.也可以通过指定的索引和分片获取元素。
  3. 元组用“()”表示。元组是只读的,不能修改。
  4. 字典用“{}”表示。字典存储键值对(key-value)数据。
  5. 集合没有特殊的表示方法,而是通过一个set函数转换成集合。

3、英文词频统计实例

  1. 待分析字符串
  2. 分解提取单词
    1. 大小写 txt.lower()
    2. 分隔符'.,:;?!-_’
    3. 单词列表
  3. 单词计数字典
str='''However,Xi wants more effort to be taken to build a safer China.
The authorities involved should be aware of the difficulties and challenges,
carefully analyze the current situation of Chinese society,
adopt technological innovation methods and improve the capacity to forecast
and prevent risks, he said.
"I'm excited and inspired after listening to the president's remarks,
which made a comprehensive summary of social
governance in the past five years and outlined the new
requirements and tasks in the future,"
said Huang Ming, vice-minister of public security.'''
print('待分析字符串',str)
for i in ',.?!\n':
   str=str.replace(i,' ')
str=str.lower()
str=str.split(" ")
print('单词计数词典')
words=set(str)
d={}
d['star']=str.count('star')
for a in words:
   d[a]=str.count(a)
for a in d:
   print("{0:<11}{1}".format(a,d[a]))

 

 

posted @ 2017-09-22 18:20  029郭媚婷  阅读(89)  评论(0编辑  收藏  举报