作业的要求来自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2696
1.列表,元组,字典,集合分别如何增删改查及遍历。
列表操作如下:
#列表 list1 = ['Google', 'Runoob', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"]; #输出 print(list1); print(list2); print(list3); print(list2[0:2]);'下标0开始,下标2结束,但不包含下标2所对应的上键(元素)' #增加 list1.insert(2,'Wiki'); list1.insert(5,1998); print(list1); #删除 list2.pop(0); print(list2) #修改 list3[1]='A'; print(list3); #查找 index=list3.index('b'); print(index);
元组的操作如下:
#元组 tup1 = ('Google', 'Runoob', 1997, 2000); tup2 = (1, 2, 3, 4, 5, 8); tup3 = "a", "b", "c", "d"; #输出 print(tup1); print(tup2); print(tup3); print(tup1[0]); print(tup2[1:3]); #连接元组 tup4=tup1+tup2+tup3; print(tup4); #不能删,会提示错误 del tup1; print (tup1);
字典的操作如下:
#字典 dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} #输出 print(dict) #增加 dict['Sex']='boy' #字典可以自动添加 print(dict) #删除 del dict['Name'] # 删除键 'Name' dict.clear() # 清空字典 del dict # 删除字典 print ("dict['Age']: ", dict['Age'])'但这会引发一个异常,因为用执行 del 操作后字典不再存在' #修改 dict['Age'] = 18 print(dict) #查询 if 'Age' in dict: print("键 Age 存在") else : print("键 Age 不存在")
集合的操作如下:
#集合 basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket);'z自动去重' #增加 basket.add('peach') print(basket); #删除 basket.remove('orange') print(basket); #查询 a='orange' in basket print(a)
2.总结列表,元组,字典,集合的联系与区别。参考以下几个方面:
- 括号
- 有序无序
- 可变不可变
- 重复不可重复
- 存储与查找方式
列表 | 元组 | 字典 | 集合 | |
括号 | [] | () | {} | {}或set() |
有序无序 | 有序 | 有序 | 无序 | 无序,自动正序 |
可变不可变 | 可变 | 不可变 | 可变 | 不可变 |
重复不重复 | 是 | 是 | 否 | 是 |
存储方式 | 值 | 值 | 键(不可重复) | 键值对(键不能重复) |
3.词频统计
1.下载一长篇小说,存成utf-8编码的文本文件 file
2.通过文件读取字符串 str
3.对文本进行预处理
4.分解提取单词 list
5.单词计数字典 set , dict
6.按词频排序 list.sort(key=lambda),turple
7.排除语法型词汇,代词、冠词、连词等无语义词
-
- 自定义停用词表
- 或用stops.txt
8.输出TOP(20)
9.可视化:词云
# -*- coding: utf-8 -*- """ Created on Mon Mar 11 11:29:03 2019 @author: Administrator """ exclude={'a','the','and','i','you','in','but','not','with','by','its','for','of','an','to'} #定义数组# #读取Harry Potter.txt文件中的英文内容# def gettxt(): sep=".,:;?!-_'" txt=open('Pioneers Of France In The New World France and England in North America.txt','r',encoding='utf-8').read().lower() for ch in sep : txt=txt.replace(ch,' ') return txt #分解提取单词# bigList=gettxt().split() print(bigList); print('big:',bigList.count('big')) bigSet=set(bigList) #过滤单词,包括一些冠词和连词等# bigSet=bigSet-exclude print(bigSet) #单词计数# bigDict={} for word in bigSet: bigDict[word]=bigList.count(word) print(bigDict) print(bigDict.items()) word=list(bigDict.items()) #按词频排序# word.sort(key=lambda x:x[1],reverse=True) print(word) #输出频率较高的词语top20# for i in range(20): print(word[i]) #排序好的单词列表word保存成csv文件# import pandas as pd pd.DataFrame(data=word).to_csv('Pioneers Of France In The New World: France and England in North America.csv',encoding='utf-8')
运行结果如下:
输出csv文件
使用网站(https://wordart.com/create)进行词云统计,结果如下: