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

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

>>> ls=list('3232423132323')
>>> ls
['3', '2', '3', '2', '4', '2', '3', '1', '3', '2', '3', '2', '3']
>>> ls.append('5')
>>> ls
['3', '2', '3', '2', '4', '2', '3', '1', '3', '2', '3', '2', '3', '5']
>>> ls.pop(2)
'3'
>>> ls
['3', '2', '2', '4', '2', '3', '1', '3', '2', '3', '2', '3', '5']
>>> ls.index('3')
0
>>> ls.count('1')
1
>>> ls.count('3')
5
>>> ls.insert(2,'2')
>>> ls
['3', '2', '2', '2', '4', '2', '3', '1', '3', '2', '3', '2', '3', '5']
>>> 

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

>>> d={'09':'66','05':'80','14':'78','23':'90'}
>>> d['14']
'78'
>>> 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','66')
'80'
>>> d.pop('23','80')
'90'
>>> d
{'09': '66', '05': '80', '14': '78'}
>>> '04' in d
False
>>> '05'in d
True
>>> del(d['09'])
>>> d
{'05': '80', '14': '78'}>>> d["02"]="90"
>>> d{'05': '80', '14': '78', '02': '90'}

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

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

>>> a=list('1123231132213')
>>> b=tuple('1123231132213')
>>> d={'09':'66','05':'80','14':'78','23':'90'}
>>> s=set('1123231132213')
>>> a
['1', '1', '2', '3', '2', '3', '1', '1', '3', '2', '2', '1', '3']
>>> b
('1', '1', '2', '3', '2', '3', '1', '1', '3', '2', '2', '1', '3')
>>> d
{'09': '66', '05': '80', '14': '78', '23': '90'}
>>> s
{'1', '3', '2'}
>>> for i in a:
    print(i,end='')
>>> for i in b:
    print(i,end='')
>>> for i in d:
    print(i,end='')
>>> for i in d:
    print(i,d.values())
dict_values(['66', '80', '78', '90'])
dict_values(['66', '80', '78', '90'])
dict_values(['66', '80', '78', '90'])
dict_values(['66', '80', '78', '90'])
>>>  for i in s:
    print(i,end='')
    
SyntaxError: unexpected indent
>>> for i in s:
    print(i,end='')
>>>

列表:列表是一些可以重复,类型不同的元素的一个清单这样子的一个东西,可读可修改,符号为[],可以使用append、pop等进行增删改计数操作等。

元组:和列表的不同之处在于只读不可修改,符号为()。

字典:字典里面存的是值对,有键和值得区分,符号为{}。

集合:可以通过set函数实现集合,集合的符号也是{}

4.英文词频统计实例

1.待分析字符串 

2.分解提取单词

3.大小写 txt.lower()

4.分隔符'.,:;?!-_’

5.计数字典

6.排序list.sort()

 7.输出TOP(10)

news=news.lower()

for i in ",.'-":
    news=news.replace(i,'')
words=news.split(' ')
keys=set(words)
#print(keys)
dic={}
for i in words:
    dic[i]=words.count(i)
#print(dic)
a=list(dic.items())
a.sort(key=lambda x:x[1],reverse=True)
#print(a)
for i in range(10):
    print(a[i])

结果:

('you', 13)
('Guangzhou', 10)
('and', 10)
('the', 10)
('is', 9)
('a', 9)
('city', 8)
('can', 8)
('in', 8)
('to', 7)
>>> 
原文地址:https://www.cnblogs.com/huanglinxin/p/7562573.html