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

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

# 定义一个列表
textList = ['cd','rm','mkdir','cat','tar']

# 增加
textList.append('gunzip')
textList.insert(2 , 'qzip')

# 删除
textList.pop(1)
del textList[3]

# 修改
textList[1] = 'love'

# 遍历
for i in range(len(textList)):
print(textList[i])

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

(元组)

tup=('语文','数学','英语',0)
tup2=('CM',)
tup3=tup+tup2
print("连接/增加元素 :{}".format(tup3))

#访问元素
tup=('语文','数学','英语',0)
print("访问元素 :tup[2]={},tup[0:1]={}".format(tup3[2],tup[0:2]))

#删除元素
tup=('语文','数学','英语',0)
print("删除元组")
del tup

#遍历元素
tup=('语文','数学','英语',0)
print("遍历元组:")
for t in tup:
print(t)

(字典)

# 创建字典
textDict = {'张三':'80','李四':'90','王五':'95'}
print(textDict)

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

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

# 删除
del textDict['张三']
print(textDict)

# 查找
print(textDict['李四'])

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

(集合)

set=set(["语文","数学","英语","化学","地理"]);
print("集合:",set);

set.add("语文");
print("增加‘语文’(无法增加,set中午重复值):",set);
set.add("生物");
print("增加‘生物’:",set);

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

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

 

 

3.词频统计

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')
  • 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.可视化:词云如下图

 

posted @ 2019-03-14 17:13  黄志鹏062  阅读(111)  评论(0编辑  收藏  举报