复合数据类型,英文词频统计
1.列表,元组,字典,集合分别如何增删改查及遍历。
(1)列表
# 增
# append:末尾添加
a = ['A', 'B', 'C']
a.append('D')
print(a)
# insert:指定位置添加
a = ['A', 'B', 'C']
a.insert(2, 'D')
print(a)
# extend:分解在末尾添加
a = ['A', 'B', 'C']
a.extend('DEF')
print(a)
# 删
# pop:指定位置删除
a = ['A', 'B', 'C']
a.pop(0)
print(a)
# remove:删除指定元素
a = ['A', 'B', 'C']
a.remove('B')
print(a)
# clear:清空列表元素
a = ['A', 'B', 'C']
a.clear()
print(a)
#改
# 元素赋值
a = ['A', 'B', 'C']
a[2] = 'D'
print(a)
# 分片赋值
a = ['A', 'B', 'C']
a[0:2] = 'D'
print(a)
#查
# 下标取值
a = ['A', 'B', 'C']
print(a[1])
#遍历
# 使用for循环
a = ['A', 'B', 'C']
num = 1
for i in a:
print("列表第%d的值:"%(num),i)
num += 1
显示结果:

(2)元组
#增
a = ('A','B')
b = ('C','D')
c = a + b
print(c)
#删
c = ('AAA','BBB')
print("删除元组c")
del c
#查
c = ('A','B','C','D')
print("第一个:{} 第二个:{}".format(c[0],c[1]))
#遍历
c = ('A','B','C','D')
for d in c:
print(d)
显示结果:

(3)字典
#增
dict = {'a':10,'b':9,'c':8}
dict['d'] = 7
print(dict)
#删
dict = {'a':10,'b':9,'c':8}
del dict['a']
print(dict)
#改
dict = {'a':10,'b':9,'c':8}
dict['a'] = 7
print(dict)
#查
dict = {'a':10,'b':9,'ccc':8}
print("查找:{}".format(dict['a']))
# 遍历
dict = {'a':10,'b':9,'c':8}
for bl in dict:
print("{}:{}".format(bl,dict[bl]))
显示结果:

(4)集合
a=set('a')
a.add('b') #增加元素
a.remove('b') 或者 a.discard('b') #删除元素
a.pop() #随机删除元素
2.总结列表,元组,字典,集合的联系与区别。参考以下几个方面:
- 括号------ (1)列表:[ ] (2)元组:( ) (3)字典:{ } (4) 集合:( )
- 有序无序------(1)有序 (2)有序 (3)无序 (4)无序
- 可变不可变-----(1)可变 (2)可变 (3)不可变,元组中的元素不可修改、不可删除(4)可变
- 重复不可重复-----(1)可以重复(2)可以重复(3)可以重复(4)不可以重复
- 存储与查找方式------(1)① 找出某个值第一个匹配项的索引位置,如:list.index(‘a’)② 使用下标索引,如:list[1] (2)使用下标索引,如:tuple[1](3)通过使用相应的键来查找,如:dict[‘a’] (4)通过判断元素是否在集合内,如:1 in dict
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.可视化:词云
排序好的单词列表word保存成csv文件
import pandas as pd
pd.DataFrame(data=word).to_csv('big.csv',encoding='utf-8')
线上工具生成词云:
https://wordart.com/create
f = open(r'hhh.txt', encoding='utf8')
# 打开文件
stop = { 'the', 'and', 'it', 'of', 'in', 'a', 'at', 'out', 'was', 'but', 'not', 'to', 'said', 'me',
'for', 'she'}
def gettext():
sep = "~`*()!<>?,./;'\:[]{}-=_+"
text = f.read().lower()
for s in sep:
text = text.replace(s, '')
return text
# 读取文件
textList = gettext().split()
print(textList)
# 分解提取单词
textSet = set(textList)
stop = set(stop)
textSet = textSet - stop
print(textSet)
# 排除语法词
textDict = {}
for word in textSet:
textDict[word] = textList.count(word)
print(textDict)
print(textDict.items())
word = list(textDict.items())
# 单词计数
word.sort(key=lambda x: x[1], reverse=True)
print(word)
# 排序
for q in range(20):
print(word[q])
# 次数为前20的单词
import pandas as pd
pd.DataFrame(data=word).to_csv("text.csv", encoding='utf-8')



浙公网安备 33010602011771号