1.列表,元组,字典,集合分别如何增删改查及遍历。
2.总结列表,元组,字典,集合的联系与区别。参考以下几个方面:
- 括号
- 有序无序
- 可变不可变
- 重复不可重复
- 存储与查找方式
| 列表 | 元祖 | 字典 | 集合 | |
|
括号 |
[] | () | {} | {} |
|
有序无序 |
有序 | 有序 | 无序,自动正序 | 无序 |
|
可变不可变 |
可变 | 不可变 | 不可变 | 可变 |
|
重复不可重复 |
可以 | 可以 | 可以 | 不可以 |
|
存储与查找方式 |
值 | 值 | 键值对(键不能重复) | 键(不能重复) |
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)

代码:
import re
import pandas
from stop_words import get_stop_words
stop_words = get_stop_words('english')
file = open("Howl’s Moving Castle.txt", "r+", encoding='UTF-8')
str = file.read()
str = re.sub('[\r\n\t,!?:;“‘’.\"]', '', str)
words = str.split(" ")
single = [] # 分词数组
excluding_words = [] # 排除的单词
quantity = [] # 单词次数
for word in words:
if (word not in single and word not in stop_words):
single.append(word)
tmp = single.copy()
while tmp:
# print(tmp[0], "出现次数:", words.count(tmp[0]), end=" ")
quantity.append(words.count(tmp[0]))
tmp.pop(0)
dic = dict(zip(single, quantity)) # 合成字典
dic = sorted(dic.items(), key=lambda item: item[1], reverse=True) # 排序
for i in range(50):
print(dic[i][0], " : ", dic[i][1])
pandas.DataFrame(data=dic).to_csv('fenci.csv', encoding='utf-8')
print(stop_words)
file.close()
- 9.可视化:词云
排序好的单词列表word保存成csv文件
import pandas as pd
pd.DataFrame(data=word).to_csv('big.csv',encoding='utf-8')
线上工具生成词云:
https://wordart.com/create
浙公网安备 33010602011771号