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

作业来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2753

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

(1)列表

#列表list

list=["yu","shu","ying","sheng","hua"];
print("列表:",list);

list.append("wu");
print("添加wu:",list);
list.insert(2,"di");
print("添加di,索引值为2(插入到第三个位置):",list)

list.pop();
print("删除最后一个值:",list);
list.pop(2);
print("删除第三个值:",list)

list[0]="li";
print("修改第一个值:",list);

print("查找第五个值:",list[1]);

#遍历
print("遍历list:");
for l in list:
    print("\t",l);

(2)元组

tup=('yu','shu','ying',0)
tup2=('NJK',)
tup3=tup+tup2
print("连接/增加元素 :{}".format(tup3))

#访问元素
tup=('yu,'shu','ying',0)
print("访问元素 :tup[2]={},tup[0:1]={}".format(tup3[2],tup[0:2]))

#删除元素
tup=('yu','shu',‘ying’,0)
print("删除元组")
del tup

#遍历元素
tup=('yu','shu','ying',0)
print("遍历元组:")
for t in tup:
    print(t)

(3)字典

# 创建字典
textDict = {'zhang':'80','li':'90','wang':'95'}
print(textDict)

# 增加
textDict['zhao']='100'
print(textDict)

# 修改
textDict['zhang']='100'
print(textDict)

# 删除
del textDict['zhang']
print(textDict)

# 查找
print(textDict['li'])

# 遍历
for s in textDict:
    print( "%s : %s"%(s,textDict[s]))

(4)集合

set=set(["yu","shu","ying","hua","di"]);
print("集合:",set);

set.add("yu");
print("增加‘yu’(无法增加,set中午重复值):",set);
set.add("sheng");
print("增加‘sheng’:",set);

if "ying" in set:
    set.remove("ying");
print("删除‘ying’:",set); set.pop();
print("删除一个值:",set);

#遍历
print("遍历set:")
for s in set: print("\t",s);

 

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

 

1.括号

2.有序无序

3.可变不可变

4.重复不可重复

5.存储与查找方式

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.可视化:词云

代码如下:

 

import pandas as pd
import stopwords
stopwords = stopwords.get_stopwords('english')
f = open("english.txt", "r", encoding="utf-8")
str = f.read()
f.close()
remove = ",,—-。?.()?!‘’"
str = str.lower()
dict = {}
for i in remove:
str = str.replace(i, "")
list = str.split()
for word in list:
if word not in stopwords:
dict[word] = list.count(word)
d = sorted(dict.items(), reverse=True, key=lambda d: d[1])
for l in range(20):
print(d[l][0], "--", d[l][1])
pd.DataFrame(data=d).to_csv('words.csv',encoding='utf-8')

 


 


 

 词云:

 

posted on 2019-03-25 16:02  聂健凯012  阅读(177)  评论(0编辑  收藏  举报

导航