[第6周]组合数据类型-Python语言程序设计(学习笔记)
文章原创,最近更新:2018-04-19
1.辅学内容
2.集合类型及操作
3.序列类型及操作
4.实例9:基本统计值计算
5.字典类型及操作
6.模块5:jieba库的使用
7.实例10:文本词频统计
8.所有代码汇总
原链接 语言程序设计北京理工大学
1.辅学内容
1.1前课复习






1.2本课概要



1.3练习与作业

2.集合类型及操作
2.1单元开篇

2.2集合类型定义

不可改变的意思是:这个数据放到集合中,是不可修改的.比如列表类型,是可以被修改的数据类型,一旦这个数据类型放到集合中,那么集合就可能出错.因为集合要求元素是独一无二的,如果元素被改变,可能会与其他元素相同.这样集合类型就出现错误.比如整数/元组等都是集合.


关于集合的重点内容:
- 集合用大括号{}表示,元素间用逗号分隔
- 集合中每个元素唯一,不存在相同元素
- 集合元素之间无序
2.3集合操作符




2.4集合处理方法

如果一个程序出现了异常可以用try-except用这种异常处理办法捕捉这种异常.

- 因为遍历for in的时候,集合是无序的,因此输出的结果也是顺序可能与你定义的顺序不一样.
-
while Ture是指程序不断的运行.这段代码是从A中不断取出元素打印出来,当A的元素为空时,程序退出.与for in 的循环方式达到了同样的效果.但是用了不同的表达.
2.5集合类型应用场景

>>> "p" in {"p","y",123}
True
>>> {"p","y"} >= {"p","y",123}
False
>>>

这个是集合最重要的应用场景.
2.6单元小结

3.序列类型及操作
3.1单元开篇

学号序列类型能够处理很多场景.
3.2序列类型定义



3.3序列处理函数及方法




按字母的顺序进行比较.
3.4元组类型及操作




3.5列表类型及操作


没有使用[]或list(),其他方式相当于列表只是用了不同的名称.比如=,也是如此.



一般是增删改查等方式.

拿出一张纸,进行默写



全部掌握,列表问题应该没啥问题.
3.6序列类型应用场景



3.7单元小结

4.实例9:基本统计值计算
4.1”基本统计值计算“问题分析


4.2”基本统计值计算“实例讲解


def getNum():
nums =[]
iNumStr=input("请输入数字(回车退出):")
while iNumStr != "":
nums.append(eval(iNumStr))
iNumStr=input("请输入数字(回车退出):")
return nums
def mean(numbers):
s=0.0
for num in numbers:
s = s + num
return s/len(numbers)
def dev(numbers,mean):
sdev=0.0
for num in numbers:
sdev=sdev+(num-mean)**2
return pow(sdev/(len(numbers)-1),0.5)
def median(numbers):
sorted(numbers)
size=len(numbers)
if size % 2==0:
med =(numbers[size//2-1]+numbers[size//2])/2
else:
med=numbers[size//2]
return med
n=getNum()
m=mean(n)
print("平均值:{},方差{:.2},中位数:{}.".format(m,dev(n,m),median(n)))
4.3”基本统计值计算“举一反三


此处截图有误,应该是充分利用python提供的内置函数.
5.字典类型及操作
5.1单元开篇

5.2字典类型定义






集合生成空的集合,不能用{}生成,因为{}是默认生成字典的.因为字典类型在计算机编程中非常常用.所以把空的{}生成,给大字典使用.如果使用空的集合,可以使用set()函数进行生成.
5.3字典处理函数及方法

这里的k是指索引,不是数据值.

d.keys()跟d.values()里面的元素如需遍历,需要用for in 的方式进行遍历.

d.get()这个函数非常重要,在后续的例子中会使用它
d.pop相当于在字典取出值后,将字典的键值对进行删除.


用一张纸默写并进行实现
需要注意,字典元素之间是没有顺序.
字典的大部分功能都在这里.
5.4字典类型应用场景


由键k搜引对应相应的值.
5.5单元小结

6.模块5:jieba库的使用
6.1jieba库基本介绍



6.2jieba库使用说明

精确模式是最常用的模式.
搜索引擎模式在特殊的场合用的比较多.

>>> jieba.lcut("中国是一个伟大的国家")
['中国', '是', '一个', '伟大', '的', '国家']
>>> jieba.lcut("中国是一个伟大的国家",cut_all=True)
['中国', '国是', '一个', '伟大', '的', '国家']
国是是个冗余.

>>> jieba.lcut_for_search("中华人民共和国是伟大的")
['中华', '华人', '人民', '共和', '共和国', '中华人民共和国', '是', '伟大', '的']

7.实例10:文本词频统计
7.1”文本词频统计“问题分析


英文文本:Hamet 分析词频
https://python123.io/resources/pye/hamlet.txt
中文文本:《三国演义》分析人物
https://python123.io/resources/pye/threekingdoms.txt
7.2”Hamlet英文词频统计“实例讲解

有些单词有些大小写,单词之间会用空格区分。还会有逗号(,)、冒号(:)等多种符号的使用。所以对文本进行处理。规划提取每一个单词作为第一步骤。在这个基础上才有可能统计每一个单词出现的词频数量。
def getText():
txt=open("hamlet.txt","r").read()
txt=txt.lower()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt =txt.replace(ch," ")
return txt
hamletTxt=getText()
words=hamletTxt.split()
counts={}#对每个单词以及出现的次数进行映射
for word in words:
counts[word]=counts.get(word,0)+1
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)#这个列表中的sort,True排序从小到大.
for i in range (10):#前10位的单词
word,count=items[i]
print("{0:<10}{1:>5}".format(word,count))

7.3”《三国演义》人物出场统计“实例讲解(上)


7.4”《三国演义》人物出场统计“实例讲解(下)



import jieba
txt = open("threekingdoms.txt", "r", encoding='utf-8').read()
excludes={"将军","却说","荆州","二人","不可","不能","如此"}
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
elif word=="诸葛亮" or word=="孔明曰":
rword="孔明"
elif word=="关公" or word=="云长":
rword="关羽"
elif word=="玄德" or word=="玄德曰":
rword="刘备"
elif word=="孟德" or word=="丞相":
rword="曹操"
else:
rword=word
counts[rword] = counts.get(rword,0) + 1
for word in excludes:
del counts[word]
items = list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(10):
word, count = items[i]
print ("{0:<10}{1:>5}".format(word, count))
7.5”文本词频统计“举一反三


8.所有代码汇总
#CalStatisticsV1.py
def getNum(): #获取用户不定长度的输入
nums = []
iNumStr = input("请输入数字(回车退出): ")
while iNumStr != "":
nums.append(eval(iNumStr))
iNumStr = input("请输入数字(回车退出): ")
return nums
def mean(numbers): #计算平均值
s = 0.0
for num in numbers:
s = s + num
return s / len(numbers)
def dev(numbers, mean): #计算方差
sdev = 0.0
for num in numbers:
sdev = sdev + (num - mean)**2
return pow(sdev / (len(numbers)-1), 0.5)
def median(numbers): #计算中位数
sorted(numbers)
size = len(numbers)
if size % 2 == 0:
med = (numbers[size//2-1] + numbers[size//2])/2
else:
med = numbers[size//2]
return med
n = getNum() #主体函数
m = mean(n)
print("平均值:{},方差:{:.2},中位数:{}.".format(m, dev(n,m),median(n)))
Hamlet词频统计(含Hamlet原文文本)
#CalHamletV1.py
def getText():
txt = open("hamlet.txt", "r").read()
txt = txt.lower()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(ch, " ") #将文本中特殊字符替换为空格
return txt
hamletTxt = getText()
words = hamletTxt.split()
counts = {}
for word in words:
counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(10):
word, count = items[i]
print ("{0:<10}{1:>5}".format(word, count))
《三国演义》人物出场统计(上)(含《三国演义》原文文本)
#CalThreeKingdomsV1.py
import jieba
txt = open("threekingdoms.txt", "r", encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
else:
counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(15):
word, count = items[i]
print ("{0:<10}{1:>5}".format(word, count))
《三国演义》人物出场统计(下)(含《三国演义》原文文本)
#CalThreeKingdomsV2.py
import jieba
excludes = {"将军","却说","荆州","二人","不可","不能","如此"}
txt = open("threekingdoms.txt", "r", encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
elif word == "诸葛亮" or word == "孔明曰":
rword = "孔明"
elif word == "关公" or word == "云长":
rword = "关羽"
elif word == "玄德" or word == "玄德曰":
rword = "刘备"
elif word == "孟德" or word == "丞相":
rword = "曹操"
else:
rword = word
counts[rword] = counts.get(rword,0) + 1
for word in excludes:
del counts[word]
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(10):
word, count = items[i]
print ("{0:<10}{1:>5}".format(word, count))