【大数据】复合数据类型,英文词频统计

作业的要求来自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2696

1.列表,元组,字典,集合分别如何增删改查及遍历。

列表:

list = ['列表', 27,'列表',27]   #这是一个列表
#增
list.append('append')  # 增加元素到列表结尾
list.extend(['extend','扩充列表'])  # 添加指定列表的所有元素
list.insert(0, '插入元素')  #在指定位置插入一个元素
print(list)
#删
list.remove('列表')  #删除列表中值为'列表'的第一个元素
list.pop()  #删除最后一个元素
list.pop(1) #删除指定位置元素
del list[2:4]  #删除从2到4的元素 list.clear() #删除列表中的所有项 print(list) #改 list[
0] = 'list' print(list) #查 list.index('列表') #返回第一个值为x的元素的索引 print(list)

#遍历
for i in list:
print(i)

 元祖:

tup = ('Google', 'Runoob', 1997, 2000);    #这是一个元祖
#元组中的元素值是不允许修改的,但我们可以对元组进行连接组合
tup1 = (1,2,3);
tup2 = ('a', 'b','c')

# 创建一个新的元组
tup3 = tup1 + tup2;
print(tup3)

#访问元祖
print ("tup1[0]: ", tup1[0])

#遍历
for i in tup1:
print(i)

 字典:

dict = {'a': '1', 'b': '2', 'c': '3'}   #这是一个字典

#删
del dict['b'] # 删除键 'b'
dict.clear()  # 清空字典
del dict      # 删除字典
#改
dict['a'] = '9';    # 更新a
#增
dict['d'] = '4'     # 添加信息
#查
print(dict['a'])
#遍历
for i,j in dict.items():
  print(i, ":\t", j)

集合:

set1 = {1,2,3}      #这是一个集合
set2 = set((1,2,3)) #这也是一个集合
print(set1)
print(set2)

#增
set1.add(4)
print(set1)
#删
set2.remove(1)  #移除值为1的元素,如果不存在则会发生错误
set2.discard(1) #移除值为1的元素,如果不存在不会发生错误
set2.pop()      #随机删除一个元素
set2.clear()
print(set2)
#查
print(1 in set1)#存在则返回True
#集合无序,不能修改指定的元素
#遍历
for num in set1:
print(num)

2.总结列表,元组,字典,集合的联系与区别。参考以下几个方面:

  • 括号
  • 有序无序
  • 可变不可变
  • 重复不可重复
  • 存储与查找方式
  列表   元祖  字典 集合

括号

 []  ()  {} {}

有序无序

 有序  有序  无序,自动正序 无序

可变不可变

 可变  不可变  不可变 可变

重复不可重复

 可以  可以  可以 不可以

存储与查找方式

 值  值  键值对(键不能重复) 键(不能重复)

3.词频统计

  • 1.下载一长篇小说,存成utf-8编码的文本文件 file

    2.通过文件读取字符串 str

    3.对文本进行预处理

    4.分解提取单词 list

    5.单词计数字典 set , dict

    6.按词频排序 list.sort(key=lambda),turple

    7.排除语法型词汇,代词、冠词、连词等无语义词

    • 自定义停用词表
    • 或用stops.txt
import pandas as pd
from nltk.corpus import stopwords

#获取停用词
stopwords = stopwords.words('english')

f = open("Harry Potter and The Sorcerer's Stone.txt","r")
text = f.read()#读取文件
f.close()#关闭文件
#文件处理
dict = {};
text = text.lower();#小写转化
sep = ".,?:…—“”";
for s in sep:
    text = text.replace(s, " "); #以空格替换符号
list = text.split();#空格分割单词单词
for l in list:
    dict[l] = list.count(l);#获取单词数目

for s in stopwords:
     if s in dict.keys():
         dict.pop(s);#删除停用词

d = sorted(dict.items(),reverse = True,key = lambda d:d[1]); #排序

print("前20个单词出现频数为:")
for i in range(20):
    print(d[i][0]," : ",d[i][1]);

pd.DataFrame(data = d).to_csv('wordcount.csv',encoding = 'utf-8')
 #保存为.csv格式

  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

猜你喜欢

转载自www.cnblogs.com/Richard-V/p/10520197.html