PageRank算法
def create(q,graph,N): #compute Probability Matrix L = [[(1-q)/N]*N for i in range(N)] for node,edges in enumerate(graph): num_edge = len(edges) for each in edges: L[each][node] += q/num_edge return L def transform(A): n,m = len(A),len(A[0]) new_A = [[A[j][i] for j in range(n) ] for i in range(m)] return new_A def mul(A,B): n = len(A) m = len(B[0]) B = transform(B) next = [[0]*m for i in range(n)] for i in range(n): row = A[i] for j in range(m): col = B[j] next[i][j] = sum([row[k]*col[k] for k in range(n)]) return next def power(A,N): n = len(A) assert(len(A[0])==n) final_ans,temp = A,A N-=1 while N>0: if N&1: final_ans = mul(final_ans,temp) temp = mul(temp,temp) N >>=1 return final_ans def PageRank(q,graph,N): X = [[1] for i in range(N)] A = create(q,graph,N) X = mul(power(A,20),X) return X print(PageRank(0.85,[[1,2],[2],[0]],3)) ————————————————
穷人版PageRank算法的Python实现
#用于存储图 class Graph(): def __init__(self): self.linked_node_map = {}#邻接表, self.PR_map ={}#存储每个节点的入度 #添加节点 def add_node(self, node_id): if node_id not in self.linked_node_map: self.linked_node_map[node_id] = set({}) self.PR_map[node_id] = 0 else: print("这个节点已经存在") #增加一个从Node1指向node2的边。允许添加新节点 def add_link(self, node1, node2): if node1 not in self.linked_node_map: self.add_node(node1) if node2 not in self.linked_node_map: self.add_node(node2) self.linked_node_map[node1].add(node2)#为node1添加一个邻接节点,表示ndoe2引用了node1 #计算pr def get_PR(self, epoch_num=10, d=0.5):#配置迭代轮数,以及阻尼系数 for i in range(epoch_num): for node in self.PR_map:#遍历每一个节点 self.PR_map[node] = (1-d) + d*sum([self.PR_map[temp_node] for temp_node in self.linked_node_map[node]])#原始版公式 print(self.PR_map) edges = [[1,2], [3,2], [3,5], [1,3], [2,3], [3, 1], [5,1]]#模拟的一个网页链接网络 if __name__ == '__main__': graph = Graph() for edge in edges: graph.add_link(edge[0], edge[1]) graph.get_PR()
分解质因数
把一个合数分解成若干个质因数的乘积的形式,即求质因数的过程叫做分解质因数。 Python练习题问题如下: 要求:将一个正整数分解质因数;例如您输入90,分解打印90=2*3*3*5。 Python解题思路分析: 这道题需要分三部分来分解,具体分解说明如下。 1、首先当这个质数恰等于n的情况下,则说明分解质因数的过程已经结束,打印出即可。 2、如果遇到n<>k,但n能被k整除的情况,则应打印出k的值。同时用n除以k的商,作为新的正整数你n,之后再重复执行第一步的操作。 3、如果n不能被k整除时,那么用k+1作为k的值,再来重复执行第一步的操作系统。 def reduceNum(n): print ('{} = '.format(n)) if not isinstance(n, int) or n <= 0 : print ('请输入一个正确的数字') exit(0) elif n in [1] : # 如果 n 为 1 print('{}'.format(n)) while n not in [1] : # 循环保证递归 for index in range(2, n + 1) : if n % index == 0: n //= index # n 等于 n//index if n == 1: print (index) else : # index 一定是素数 print ('{} *'.format(index),end = " ") break reduceNum(90) reduceNum(100)
计算皮球下落速度 问题简述:假设一支皮球从100米高度自由落下。条件,每次落地后反跳回原高度的一半后,再落下。 要求:算出这支皮球,在它在第10次落地时,共经过多少米?第10次反弹多高?
解题思路 总共初始高度 100 米 高度 每次弹起一半距离 每一次弹起 上升的高度和下降的高度 是一次的距离 每一次弹起,高度都会是之前的一半
Sn = 100.0 Hn = Sn / 2 for n in range(2,11): Sn += 2 * Hn Hn /= 2 print ('总共经过 %.2f 米' % Sn) print ('第十次反弹 %.2f 米' % Hn)
给定年月日,判断是这一年的第几天
# 输入年月日 year = int(input('year:')) month = int(input('month:')) day = int(input('day:')) # 将正常情况下,每一个月的累计天数放入到元组中进行保存 months = (0,31,59,90,120,151,181,212,243,273,304,334) if 0 < month <= 12: # 如果输入的数据正确,月份在 1~12 之间 sum_days = months[month - 1] # 总天数就为 列表中的天数,索引值根据 输入的月份进行选择 else: print ('数据错误,请重新输入') # 加上输入的日期 sum_days += day # 默认不是闰年 leap = 0 # 判断是否是闰年,被 400 整除,可以整除4 但是不能被 100 除掉 if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)): leap = 1 # 如果为 1 则表示 这一年是闰年 if (leap == 1) and (month > 2): # 当这一年是闰年,并且月份大于 2 时,说明存在 29 日,所以总天数再增加 1 sum_days += 1 print ('这是 %d 年的第 %d 天.' % (year,sum_days))
实验1-5
Django暂时停止更新,先把学校实验报告弄完 ''' 计算 1.输入半径,输出面积和周长 2.输入面积,输出半径及周长 3.输入周长,输出半径及面积 ''' '''1.输入半径,输出面积和周长''' from math import pi '''定义半径''' r = int(input("请输入半径的值(整数)")) if r <= 0 : exit("请重新输入半径") ''' S 面积: pi * r * r ''' S = pi * pow(r,2) print(" 半径为 %d 的圆,面积为 %.2f"%(r,S)) '''C 周长: C = 2 * pi * r ''' C = 2 * pi * r print(" 半径为 %d 的圆,周长为 %.2f"%(r,C)) '''2.输入面积,输出半径及周长''' from math import pi,sqrt S = float(input("请输入圆的面积(支持小数格式)")) if S < 0 : exit("请重新输入面积") '''r 半径: r = sqrt(S/pi)''' r = sqrt(S/pi) print("面积为 %.2f 的圆,半径为 %.2f"%(S,r)) '''C 周长: C = 2 * pi * r ''' C = 2 * pi * r print("面积为 %.2f 的圆,周长为 %.2f"%(S,C)) '''3.输入周长,输出半径及面积''' from math import pi C = float(input("请输入圆的周长(支持小数格式)")) if C < 0 : exit("请重新输入周长") '''r 半径: r = C/(2*pi)''' r = C/(2*pi) print("周长为 %.2f 的圆,半径为 %.2f"%(C,r)) ''' S 面积: pi * r * r ''' S = pi * pow(r,2) print("周长为 %.2f 的圆,面积为 %.2f"%(C,S)) ''' 数据结构 列表练习 1.创建列表对象 [110,'dog','cat',120,'apple'] 2.在字符串 'dog' 和 'cat' 之间插入空列表 3.删除 'apple' 这个字符串 4.查找出 110、120 两个数值,并以 10 为乘数做自乘运算 ''' '''1.创建列表对象 [110,'dog','cat',120,'apple']''' # '''创建一个名为 lst 的列表对象''' lst = [110,'dog','cat',120,'apple'] print(lst) '''2.在字符串 'dog' 和 'cat' 之间插入空列表''' lst = [110,'dog','cat',120,'apple'] '''添加元素到 'dog' 和 'cat' 之间''' lst.insert(2,[]) print(lst) '''3.删除 'apple' 这个字符串''' lst = [110,'dog','cat',120,'apple'] '''删除最后一个元素''' lst.pop() print(lst) '''4.查找出 110、120 两个数值,并以 10 为乘数做自乘运算''' lst = [110,'dog','cat',120,'apple'] try: '''如果找不到数据,进行异常处理''' lst[lst.index(110)] *= 10 lst[lst.index(120)] *= 10 except Exception as e: print(e) print(lst) ''' 元组练习 1.创建列表 ['pen','paper',10,False,2.5] 赋给变量并查看变量的类型 2.将变量转换为 tuple 类型,查看变量的类型 3.查询元组中的元素 False 的位置 4.根据获得的位置提取元素 ''' '''1.创建列表 ['pen','paper',10,False,2.5] 赋给变量并查看变量的类型''' lst = ['pen','paper',10,False,2.5] '''查看变量类型''' print("变量的类型",type(lst)) '''2.将变量转换为 tuple 类型,查看变量的类型''' lst = tuple(lst) print("变量的类型",type(lst)) '''3.查询元组中的元素 False 的位置''' if False in lst: print("False 的位置为(从0开始): ",lst.index(False)) '''4.根据获得的位置提取元素''' print("根据获得的位置提取的元素为: ",lst[lst.index(False)]) else: print("不在元组中") ''' 1.创建字典{‘Math’:96,’English’:86,’Chinese’:95.5, ’Biology’:86,’Physics’:None} 2.在字典中添加键对{‘Histore’:88} 3.删除{’Physics’:None}键值对 4.将键‘Chinese’所对应的值进行四舍五入后取整 5.查询键“Math”的对应值 ''' '''1.创建字典''' dic = {'Math':96,'English':86,'Chinese':95.5,'Biology':86,'Physics':None} print(dic) '''2.添加键值对''' dic['Histore'] = 88 print(dic) '''3.删除{’Physics’:None}键值对''' del dic['Physics'] print(dic) '''4.将键‘Chinese’所对应的值进行四舍五入后取整''' print(round(dic['Chinese'])) '''5.查询键“Math”的对应值''' print(dic['Math']) ''' 1.创建列表[‘apple’,’pear’,’watermelon’,’peach’]并赋给变量 2.用list()创建列表[‘pear’,’banana’,’orange’,’peach’,’grape’],并赋给变量 3.将创建的两个列表对象转换为集合类型 4.求两个集合的并集、交集和差集 ''' '''1.创建列表''' lst = ['apple','pear','watermelon','peach'] print(lst) '''2.用list()创建,并赋给变量''' lstTwo = list(('pear','banana','orange','peach','grape')) print(lstTwo) '''3.将创建的两个列表对象转换为集合类型''' lst = set(lst) lstTwo = set(lstTwo) '''4.求两个集合的并集、交集和差集''' print("并集是:",lst | lstTwo) print("交集是:",lst & lstTwo) print("差集:") print(lst - lstTwo) print(lstTwo - lst) ''' 1 输出数字金字塔 (1)设置输入语句,输入数字 (2)创建变量来存放金字塔层数 (3)编写嵌套循环,控制变量存放每一层的长度 (4)设置条件来打印每一行输出的数字 (5)输出打印结果 ''' num = int(input("请输入金字塔的层数")) '''cs 层数''' cs = 1 while cs <= num: kk = 1 t = cs length = 2*t - 1 while kk <= length: if kk == 1: if kk == length: print(format(t,str(2*num-1)+"d"),'\n') break else: print(format(t,str(2*num+1 - 2*cs) + "d"),"",end = "") t -= 1 else: if kk == length: '''最右侧数字 length 位置上数字为 t''' print(t,"\n") break elif kk <= length/2: '''到中间的数字不断减小''' print(t,"",end = "") t -= 1 else: '''中间的数字到右侧的数字不断增大''' print(t,"",end = "") t += 1 kk += 1 '''层数加 1''' cs += 1 ''' (1)使用自定义函数,完成对程序的模块化 (2)学生信息至少包括:姓名、性别及手机号 (3)该系统具有的功能:添加、删除、修改、显示、退出系统 ''' '''创建一个容纳所有学生的基本信息的列表''' stusInfo = [] def menu(): '''定义页面显示''' print('-'*20) print('学生管理系统') print('1.添加学生信息') print('2.删除学生信息') print('3.修改学生信息') print('4.显示所有学生信息') print('0.退出系统') print('-' * 20) def addStuInfo(): '''添加学生信息''' '''设置变量容纳学生基本信息''' newStuName = input('请输入新学生的姓名') newStuGender = input('请输入新学生的性别') newStuPhone = input('请输入新学生的手机号') '''设置字典将变量保存''' newStudent = {} newStudent['name'] = newStuName newStudent['gender'] = newStuGender newStudent['phone'] = newStuPhone '''添加到信息中''' stusInfo.append(newStudent) def delStuInfo(): '''删除学生信息''' showStusInfo() defStuId = int(input('请输入要删除的序号:')) '''从列表中删除 该学生''' del stusInfo[defStuId - 1] def changeStuInfo(): '''修改学生信息''' showStusInfo() '''查看修改的学生序号''' stuId = int(input("请输入需要修改的学生的序号: ")) changeStuName = input('请输入修改后的学生的姓名') changeStuGender = input('请输入修改后的学生的性别') changeStuPhone = input('请输入修改后的学生的手机号') '''对列表修改学生信息''' stusInfo[stuId - 1]['name'] = changeStuName stusInfo[stuId - 1]['gender'] = changeStuGender stusInfo[stuId - 1]['phone'] = changeStuPhone def showStusInfo(): print('-'*30) print("学生的信息如下:") print('-'*30) print('序号 姓名 性别 手机号码') '''展示学生序号(位置),姓名,性别,手机号码''' stuAddr = 1 for stuTemp in stusInfo: print("%d %s %s %s"%(stuAddr,stuTemp['name'],stuTemp['gender'],stuTemp['phone'])) stuAddr += 1 def main(): '''主函数''' while True: '''显示菜单''' menu() keyNum = int(input("请输入功能对应的数字")) if keyNum == 1: addStuInfo() elif keyNum == 2: delStuInfo() elif keyNum == 3: changeStuInfo() elif keyNum == 4: showStusInfo() elif keyNum == 0: print("欢迎下次使用") break if __name__ == '__main__': main() import numpy as np '''一维数组''' '''np.array 方法''' print(np.array([1,2,3,4])) # [1 2 3 4] print(np.array((1,2,3,4))) # [1 2 3 4] print(np.array(range(4))) # [0 1 2 3] '''np.arange 方法''' print(np.arange(10)) # [0 1 2 3 4 5 6 7 8 9] '''np.linspace 方法''' print(np.linspace(0,10,11)) # [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.] print(np.linspace(0,10,11,endpoint = False)) # [0. 0.90909091 1.81818182 2.72727273 3.63636364 4.54545455 # 5.45454545 6.36363636 7.27272727 8.18181818 9.09090909] '''np.logspace 方法''' print(np.logspace(0,100,10)) # [1.00000000e+000 1.29154967e+011 1.66810054e+022 2.15443469e+033 # 2.78255940e+044 3.59381366e+055 4.64158883e+066 5.99484250e+077 # 7.74263683e+088 1.00000000e+100] print(np.logspace(1,4,4,base = 2)) # [ 2. 4. 8. 16.] '''zeros 方法''' print(np.zeros(3)) # [0. 0. 0.] '''ones 方法''' print(np.ones(3)) # [1. 1. 1.] '''二维数组''' '''np.array 方法''' print(np.array([[1,2,3],[4,5,6]])) # [[1 2 3] # [4 5 6]] '''np.identify 方法''' print(np.identity(3)) # [[1. 0. 0.] # [0. 1. 0.] # [0. 0. 1.]] '''np.empty 方法''' print(np.empty((3,3))) # [[1. 0. 0.] # [0. 1. 0.] # [0. 0. 1.]] '''np.zeros 方法''' print(np.zeros((3,3))) # [[0. 0. 0.] # [0. 0. 0.] # [0. 0. 0.]] '''np.ones 方法''' print(np.ones((3,3))) # [[1. 1. 1.] # [1. 1. 1.] # [1. 1. 1.]] import numpy as np '''一维数组''' '''np.random.randint 方法''' print(np.random.randint(0,6,3)) # [4 2 1] '''np.random.rand 方法''' print(np.random.rand(10)) # [0.12646424 0.59660184 0.52361248 0.1206141 0.28359949 0.46069696 # 0.18397493 0.73839455 0.99115088 0.98297331] '''np.random.standard_normal 方法''' print(np.random.standard_normal(3)) # [-0.12944733 -0.32607943 0.58582095] '''二维数组''' '''np.random.randint 方法''' print(np.random.randint(0,6,(3,3))) # [[0 0 0] # [4 4 0] # [5 0 3]] '''多维数组''' print(np.random.standard_normal((3,4,2))) # [[[-0.79751104 -1.40814148] # [-1.06189896 1.19993648] # [ 1.68883868 0.09190824] # [ 0.33723433 0.28246094]] # # [[ 0.3065646 1.1177714 ] # [-0.48928572 0.55461195] # [ 0.3880272 -2.27673705] # [-0.97869759 -0.07330554]] # # [[ 0.62155155 -0.17690222] # [ 1.61473949 -0.34930031] # [-1.41535777 1.32646137] # [-0.22865775 -2.00845225]]] import numpy as np n = np.array([10,20,30,40]) print(n + 5) # [15 25 35 45] print(n - 10) # [ 0 10 20 30] print(n * 2) # [20 40 60 80] print(n / 3) # [ 3.33333333 6.66666667 10. 13.33333333] print(n // 3) # [ 3 6 10 13] print(n % 3) # [1 2 0 1] print(n ** 2) # [ 100 400 900 1600] n = np.array([1,2,3,4]) print(2 ** n) # [ 2 4 8 16] print(16//n) # [16 8 5 4] print(np.array([1,2,3,4]) + np.array([1,1,2,2])) # [2 3 5 6] print(np.array([1,2,3,4]) + np.array(4)) # [5 6 7 8] print(n) # [1 2 3 4] print(n + n) # [2 4 6 8] print(n - n) # [0 0 0 0] print(n * n) # [ 1 4 9 16] print(n / n) # [1. 1. 1. 1.] print(n ** n) # [ 1 4 27 256] x = np.array([4,7,3]) print(np.argsort(x)) # [2 0 1] print(x.argmax()) # 1 print(x.argmin()) # 2 print(np.sort(x)) # [3 4 7] print(np.where(x < 5,0,1)) x = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(x) # [[1 2 3] # [4 5 6] # [7 8 9]] x.resize((2,5)) print(x) # [[1 2 3 4 5] # [6 7 8 9 0]] print(np.piecewise(x,[x<3],[lambda x:x + 1])) # [[2 3 0 0 0] # [0 0 0 0 1]] import pandas as pd import numpy as np '''对 sepal_length 这一列进行分析''' irisSepalLength = np.loadtxt('iris.csv') print(irisSepalLength[:5]) # [5.1 4.9 4.7 4.6 5. ] '''对数据进行排序''' irisSepalLength.sort() print(irisSepalLength[:15]) # [4.3 4.4 4.4 4.4 4.5 4.6 4.6 4.6 4.6 4.7 4.7 4.8 4.8 4.8 4.8] '''查看去重后的数据集''' print(np.unique(irisSepalLength)[:15]) # [4.3 4.4 4.5 4.6 4.7 4.8 4.9 5. 5.1 5.2 5.3 5.4 5.5 5.6 5.7] '''查看长度的总和''' print(np.sum(irisSepalLength)) # 876.5 '''累计和''' print(np.cumsum(irisSepalLength)[:10]) # [ 4.3 8.7 13.1 17.5 22. 26.6 31.2 35.8 40.4 45.1] '''均值''' print(np.mean(irisSepalLength)) # 5.843333333333334 '''标准差''' print(np.std(irisSepalLength)) # 0.8253012917851409 '''方差''' print(np.var(irisSepalLength)) # 0.6811222222222223 '''最小值''' print(np.min(irisSepalLength)) # 4.3 '''最大值''' print(np.max(irisSepalLength)) # 7.9 import pandas as pd '''创建 Series 对象 s''' s = pd.Series(range(1,20,5)) print(s) # 0 1 # 1 6 # 2 11 # 3 16 # dtype: int64 s = pd.Series({'语文':90,'数学':92,'物理':88,'化学':99}) print(s) # 语文 90 # 数学 92 # 物理 88 # 化学 99 # dtype: int64 '''修改数据''' s['语文'] = 100 print(s) # 语文 100 # 数学 92 # 物理 88 # 化学 99 # dtype: int64 '''使用绝对值''' print(abs(s)) # 语文 100 # 数学 92 # 物理 88 # 化学 99 # dtype: int64 '''对数据列加后缀''' # s.add_suffix('后缀') '''查看某些数据是否满足条件''' print(s.between(90,99,inclusive = True)) # 语文 False # 数学 True # 物理 False # 化学 True # dtype: bool '''查看属性最大的列名''' print(s.idxmax()) # 语文 '''查看属性最小的列名''' print(s.idxmin()) # 物理 '''大于 95 的列''' print(s[s > 95]) # 语文 100 # 化学 99 # dtype: int64 '''查看中值''' print(s.median()) # 95.5 '''大于中值的列''' print(s[s > s.median()]) # 语文 100 # 化学 99 # dtype: int64 '''查看最小的 3 个值''' print(s.nsmallest(3)) # 物理 88 # 数学 92 # 化学 99 # dtype: int64 '''查看最大的 3 个值''' print(s.nlargest(3)) # 语文 100 # 化学 99 # 数学 92 # dtype: int64 '''两个 Series 对象进行相加''' print(pd.Series(range(5)) + pd.Series(range(7,12))) # 0 7 # 1 9 # 2 11 # 3 13 # 4 15 # dtype: int64 '''对 Series 对象使用函数''' print(pd.Series(range(5)).pipe(lambda x,y:(x**y),4)) # 0 0 # 1 1 # 2 16 # 3 81 # 4 256 # dtype: int64 print(pd.Series(range(5)).pipe(lambda x:x + 3)) # 0 3 # 1 4 # 2 5 # 3 6 # 4 7 # dtype: int64 print(pd.Series(range(5)).apply(lambda x:x + 3)) # 0 3 # 1 4 # 2 5 # 3 6 # 4 7 # dtype: int64 '''查看标准差方差''' print(s) print(s.std()) # 5.737304826019502 print(s.var()) # 32.916666666666664 '''查看是否全部为真''' print(any(pd.Series([1,0,1]))) # True print(all(pd.Series([1,0,1]))) # False import pandas as pd import numpy as np '''创建一个 DataFrame 对象''' df = pd.DataFrame(np.random.randint(1,5,(5,3)),index = range(5),columns = ['A','B','C']) print(df) # A B C # 0 4 4 2 # 1 1 4 1 # 2 4 3 4 # 3 3 1 3 # 4 2 3 1 '''读取数据''' market = pd.read_excel('超市营业额.xlsx') print(market.head()) # 工号 姓名 日期 时段 交易额 柜台 # 0 1001 张三 2019-03-01 9:00-14:00 1664.0 化妆品 # 1 1002 李四 2019-03-01 14:00-21:00 954.0 化妆品 # 2 1003 王五 2019-03-01 9:00-14:00 1407.0 食品 # 3 1004 赵六 2019-03-01 14:00-21:00 1320.0 食品 # 4 1005 周七 2019-03-01 9:00-14:00 994.0 日用品 '''查看不连续行的数据''' print(market.iloc[[1,8,19],:]) # 工号 姓名 日期 时段 交易额 柜台 # 1 1002 李四 2019-03-01 14:00-21:00 954.0 化妆品 # 8 1001 张三 2019-03-02 9:00-14:00 1530.0 化妆品 # 19 1004 赵六 2019-03-03 14:00-21:00 1236.0 食品 print(market.iloc[[1,8,19],[1,4]]) # 姓名 交易额 # 1 李四 954.0 # 8 张三 1530.0 # 19 赵六 1236.0 '''查看前五条记录的 姓名 时段 和 交易额''' print(market[['姓名','时段','交易额']].head()) # 姓名 时段 交易额 # 0 张三 9:00-14:00 1664.0 # 1 李四 14:00-21:00 954.0 # 2 王五 9:00-14:00 1407.0 # 3 赵六 14:00-21:00 1320.0 # 4 周七 9:00-14:00 994.0 print(market.loc[[3,4,7],['姓名','时段','柜台']]) # 姓名 时段 柜台 # 3 赵六 14:00-21:00 食品 # 4 周七 9:00-14:00 日用品 # 7 张三 14:00-21:00 蔬菜水果 '''查看交易额大于 2000 的数据''' print(market[market.交易额 > 1500].head()) # 工号 姓名 日期 时段 交易额 柜台 # 0 1001 张三 2019-03-01 9:00-14:00 1664.0 化妆品 # 8 1001 张三 2019-03-02 9:00-14:00 1530.0 化妆品 # 14 1002 李四 2019-03-02 9:00-14:00 1649.0 蔬菜水果 # 18 1003 王五 2019-03-03 9:00-14:00 1713.0 食品 # 20 1005 周七 2019-03-03 9:00-14:00 1592.0 日用品 '''查看交易额的总和''' print(market['交易额'].sum()) # 327257.0 print(market[market['时段'] == '9:00-14:00']['交易额'].sum()) # 176029.0 '''查看某员工在 14:00-21:00 的交易数据''' print(market[(market.姓名 == '张三') & (market.时段 == '14:00-21:00')].head()) # 工号 姓名 日期 时段 交易额 柜台 # 7 1001 张三 2019-03-01 14:00-21:00 1442.0 蔬菜水果 # 39 1001 张三 2019-03-05 14:00-21:00 856.0 蔬菜水果 # 73 1001 张三 2019-03-10 14:00-21:00 1040.0 化妆品 # 91 1001 张三 2019-03-12 14:00-21:00 1435.0 食品 # 99 1001 张三 2019-03-13 14:00-21:00 1333.0 食品 '''查看交易额在 1500 到 2500 的数据''' print(market[market['交易额'].between(1500,2000)].head()) # 工号 姓名 日期 时段 交易额 柜台 # 0 1001 张三 2019-03-01 9:00-14:00 1664.0 化妆品 # 8 1001 张三 2019-03-02 9:00-14:00 1530.0 化妆品 # 14 1002 李四 2019-03-02 9:00-14:00 1649.0 蔬菜水果 # 18 1003 王五 2019-03-03 9:00-14:00 1713.0 食品 # 20 1005 周七 2019-03-03 9:00-14:00 1592.0 日用品 '''查看描述''' print(market['交易额'].describe()) # count 246.000000 # mean 1330.313008 # std 904.300720 # min 53.000000 # 25% 1031.250000 # 50% 1259.000000 # 75% 1523.000000 # max 12100.000000 # Name: 交易额, dtype: float64 print(market['交易额'].quantile([0,0.25,0.5,0.75,1])) # 0.00 53.00 # 0.25 1031.25 # 0.50 1259.00 # 0.75 1523.00 # 1.00 12100.00 # Name: 交易额, dtype: float64 '''查看中值''' print(market['交易额'].median()) # 1259.0 '''查看最大值''' print(market['交易额'].max()) # 12100.0 print(market['交易额'].nlargest(5)) # 105 12100.0 # 223 9031.0 # 113 1798.0 # 188 1793.0 # 136 1791.0 '''查看最小值''' print(market['交易额'].min()) # 53.0 print(market['交易额'].nsmallest(5)) # 76 53.0 # 97 98.0 # 194 114.0 # 86 801.0 # 163 807.0 # Name: 交易额, dtype: float64 import pandas as pd market = pd.read_excel('超市营业额.xlsx') print(market.head()) # 工号 姓名 日期 时段 交易额 柜台 # 0 1001 张三 2019-03-01 9:00-14:00 1664.0 化妆品 # 1 1002 李四 2019-03-01 14:00-21:00 954.0 化妆品 # 2 1003 王五 2019-03-01 9:00-14:00 1407.0 食品 # 3 1004 赵六 2019-03-01 14:00-21:00 1320.0 食品 # 4 1005 周七 2019-03-01 9:00-14:00 994.0 日用品 '''对数据进行排序''' print(market.sort_values(by = ['交易额','工号'],ascending = False).head()) # 工号 姓名 日期 时段 交易额 柜台 # 105 1001 张三 2019-03-14 9:00-14:00 12100.0 日用品 # 223 1003 王五 2019-03-28 9:00-14:00 9031.0 食品 # 113 1002 李四 2019-03-15 9:00-14:00 1798.0 日用品 # 188 1002 李四 2019-03-24 14:00-21:00 1793.0 蔬菜水果 # 136 1001 张三 2019-03-17 14:00-21:00 1791.0 食品 print(market.sort_values(by = ['交易额','工号'],ascending = True).head()) # 工号 姓名 日期 时段 交易额 柜台 # 76 1005 周七 2019-03-10 9:00-14:00 53.0 日用品 # 97 1002 李四 2019-03-13 14:00-21:00 98.0 日用品 # 194 1001 张三 2019-03-25 14:00-21:00 114.0 化妆品 # 86 1003 王五 2019-03-11 9:00-14:00 801.0 蔬菜水果 # 163 1006 钱八 2019-03-21 9:00-14:00 807.0 蔬菜水果 '''groupby 对象 的使用''' print(market.groupby(by = lambda x:x%3)['交易额'].sum()) # 0 113851.0 # 1 108254.0 # 2 105152.0 # Name: 交易额, dtype: float64 '''查看 柜台的交易额 ''' print(market.groupby(by = '柜台')['交易额'].sum()) # 柜台 # 化妆品 75389.0 # 日用品 88162.0 # 蔬菜水果 78532.0 # 食品 85174.0 # Name: 交易额, dtype: float64 '''查看日期个数''' print(market.groupby(by = '姓名')['日期'].count()) # 姓名 # 周七 42 # 张三 38 # 李四 47 # 王五 40 # 赵六 45 # 钱八 37 # Name: 日期, dtype: int64 '''将员工的营业额汇总出来''' print(market.groupby(by = '姓名')['交易额'].sum().apply(int)) # 姓名 # 周七 47818 # 张三 58130 # 李四 58730 # 王五 58892 # 赵六 56069 # 钱八 47618 # Name: 交易额, dtype: int64 '''查看交易额的 最大最小平均值和中值''' print(market.groupby(by = '姓名').agg(['max','min','mean','median'])['交易额']) # max min mean median # 姓名 # 周七 1778.0 53.0 1195.450000 1134.5 # 张三 12100.0 114.0 1529.736842 1290.0 # 李四 1798.0 98.0 1249.574468 1276.0 # 王五 9031.0 801.0 1472.300000 1227.0 # 赵六 1775.0 825.0 1245.977778 1224.0 # 钱八 1737.0 807.0 1322.722222 1381.0 '''处理异常值''' # 考虑使用其他数据替代 '''处理缺失值''' print(market[market['交易额'].isnull()]) # 工号 姓名 日期 时段 交易额 柜台 # 110 1005 周七 2019-03-14 14:00-21:00 NaN 化妆品 # 124 1006 钱八 2019-03-16 14:00-21:00 NaN 食品 # 168 1005 周七 2019-03-21 14:00-21:00 NaN 食品 # 考虑使用 平均值 替换 '''处理重复值''' # 考虑是否删除数据 '''duplicated() 和 drop_duplicates()''' '''使用透视表,查看前五天的数据''' print(market.pivot_table(values = '交易额',index = '姓名',columns = '日期',aggfunc = 'sum').iloc[:,:5]) print(market.pivot_table(values = '交易额',index = '姓名',columns = '柜台',aggfunc = 'count').iloc[:,:5]) '''使用交叉表,查看员工和柜台的次数''' print(pd.crosstab(market['姓名'],market['柜台'])) # 姓名 # 周七 9 11 14 8 # 张三 19 6 6 7 # 李四 16 9 18 4 # 王五 8 9 9 14 # 赵六 10 18 2 15 # 钱八 0 9 14 14 print(pd.crosstab(market['姓名'],market['日期'])) # 日期 2019-03-01 2019-03-02 2019-03-03 ... 2019-03-29 2019-03-30 2019-03-31 # 姓名 ... # 周七 1 1 2 ... 1 1 2 # 张三 2 1 1 ... 1 2 0 # 李四 1 2 1 ... 2 2 2 # 王五 1 2 1 ... 1 1 1 # 赵六 1 1 2 ... 2 1 2 # 钱八 2 1 1 ... 1 1 1 print(pd.crosstab(market['姓名'],market['柜台'],market['交易额'],aggfunc = 'mean').apply(lambda x:round(x))) # 柜台 化妆品 日用品 蔬菜水果 食品 # 姓名 # 周七 1190.0 1169.0 1174.0 1285.0 # 张三 1209.0 3105.0 1211.0 1323.0 # 李四 1279.0 1123.0 1292.0 1224.0 # 王五 1264.0 1262.0 1164.0 1925.0 # 赵六 1232.0 1294.0 1264.0 1196.0 # 钱八 NaN 1325.0 1326.0 1318.0
学生成绩表数据包括:学号,姓名,高数,英语和计算机三门课成绩,计算每个学生总分,每课程平均分,最高分和最低分
''' 每一个学生的总分,每个课程的平均分,最高分,最低分 ''' # 创建学生列表 stuLst = [] # 创建学生信息 stu1 = {'学号':'1001','姓名':'小明','高数':95,'英语':88,'计算机':80} stu2 = {'学号':'1002','姓名':'小李','高数':84,'英语':70,'计算机':60} stu3 = {'学号':'1003','姓名':'小王','高数':79,'英语':78,'计算机':75} # 将学生列表加入到学生信息中 stuLst.append(stu1) stuLst.append(stu2) stuLst.append(stu3) def sumScore(stuLst): '''计算每名学生的总分''' for stu in stuLst: print(stu['姓名'],"的三科总分是 ",stu['高数'] + stu['英语'] + stu['计算机']) def meanScore(stuLst): '''计算课程的平均分''' sumProjectScore_gs = 0 # 设置高数学科总分 sumProjectScore_yy = 0 # 设置英语学科总分 sumProjectScore_jsj = 0 # 设置计算机学科总分(_拼音缩写) for stu in stuLst: sumProjectScore_gs += stu['高数'] sumProjectScore_yy += stu['英语'] sumProjectScore_jsj += stu['计算机'] print("高数的平均分是 %.2f"%(sumProjectScore_gs//len(stuLst))) print("英语的平均分是 %.2f" % (sumProjectScore_yy // len(stuLst))) print("计算机的平均分是 %.2f" % (sumProjectScore_jsj // len(stuLst))) def maxScore(stuLst): '''求最大值''' # 高数 英语 计算机 gs = [] yy = [] jsj = [] for stu in stuLst: gs.append(stu['高数']) yy.append(stu['英语']) jsj.append(stu['计算机']) print("高数的最高分是 %.2f"%(max(gs))) print("英语的最高分是 %.2f" % (max(yy))) print("计算机的最高分是 %.2f" % (max(jsj))) def minScore(stuLst): '''求最小值''' # 高数 英语 计算机 gs = [] yy = [] jsj = [] for stu in stuLst: gs.append(stu['高数']) yy.append(stu['英语']) jsj.append(stu['计算机']) print("高数的最低分是 %.2f" % (min(gs))) print("英语的最低分是 %.2f" % (min(yy))) print("计算机的最低分是 %.2f" % (min(jsj))) sumScore(stuLst) meanScore(stuLst) maxScore(stuLst) minScore(stuLst)
四位玫瑰数 for i in range(1000,10000): t=str(i) if pow(eval(t[0]),4)+pow(eval(t[1]),4)+pow(eval(t[2]),4)+pow(eval(t[3]),4) == i: print(i)
四平方和
import math def f(n): if isinstance(n,int): for i in range(round(math.sqrt(n))): for j in range(round(math.sqrt(n))): for k in range(round(math.sqrt(n))): h = math.sqrt(n - i*i - j*j - k*k) # 剪掉使用了的值 if h == int(h): print("(%d,%d,%d,%d)"%(i,j,k,h)) return else: print("(0,0,0,0)") f(5) f(12) f("aaa")
学生管理系统-明日学院的
import re # 导入正则表达式模块 import os # 导入操作系统模块 filename = "students.txt" # 定义保存学生信息的文件名 def menu(): # 输出菜单 print(''' ╔———————学生信息管理系统————————╗ │ │ │ =============== 功能菜单 =============== │ │ │ │ 1 录入学生信息 │ │ 2 查找学生信息 │ │ 3 删除学生信息 │ │ 4 修改学生信息 │ │ 5 排序 │ │ 6 统计学生总人数 │ │ 7 显示所有学生信息 │ │ 0 退出系统 │ │ ========================================== │ │ 说明:通过数字或↑↓方向键选择菜单 │ ╚———————————————————————╝ ''') def main(): ctrl = True # 标记是否退出系统 while (ctrl): menu() # 显示菜单 option = input("请选择:") # 选择菜单项 option_str = re.sub("\D", "", option) # 提取数字 if option_str in ['0', '1', '2', '3', '4', '5', '6', '7']: option_int = int(option_str) if option_int == 0: # 退出系统 print('您已退出学生成绩管理系统!') ctrl = False elif option_int == 1: # 录入学生成绩信息 insert() elif option_int == 2: # 查找学生成绩信息 search() elif option_int == 3: # 删除学生成绩信息 delete() elif option_int == 4: # 修改学生成绩信息 modify() elif option_int == 5: # 排序 sort() elif option_int == 6: # 统计学生总数 total() elif option_int == 7: # 显示所有学生信息 show() '''1 录入学生信息''' def insert(): stdentList = [] # 保存学生信息的列表 mark = True # 是否继续添加 while mark: id = input("请输入ID(如 1001):") if not id: # ID为空,跳出循环 break name = input("请输入名字:") if not name: # 名字为空,跳出循环 break try: english = int(input("请输入英语成绩:")) python = int(input("请输入Python成绩:")) c = int(input("请输入C语言成绩:")) except: print("输入无效,不是整型数值....重新录入信息") continue stdent = {"id": id, "name": name, "english": english, "python": python, "c": c} # 将输入的学生信息保存到字典 stdentList.append(stdent) # 将学生字典添加到列表中 inputMark = input("是否继续添加?(y/n):") if inputMark == "y": # 继续添加 mark = True else: # 不继续添加 mark = False save(stdentList) # 将学生信息保存到文件 print("学生信息录入完毕!!!") # 将学生信息保存到文件 def save(student): try: students_txt = open(filename, "a") # 以追加模式打开 except Exception as e: students_txt = open(filename, "w") # 文件不存在,创建文件并打开 for info in student: students_txt.write(str(info) + "\n") # 按行存储,添加换行符 students_txt.close() # 关闭文件 '''2 查找学生成绩信息''' def search(): mark = True student_query = [] # 保存查询结果的学生列表 while mark: id = "" name = "" if os.path.exists(filename): # 判断文件是否存在 mode = input("按ID查输入1;按姓名查输入2:") if mode == "1": id = input("请输入学生ID:") elif mode == "2": name = input("请输入学生姓名:") else: print("您的输入有误,请重新输入!") search() # 重新查询 with open(filename, 'r') as file: # 打开文件 student = file.readlines() # 读取全部内容 for list in student: d = dict(eval(list)) # 字符串转字典 if id != "": # 判断是否按ID查 if d['id'] == id: student_query.append(d) # 将找到的学生信息保存到列表中 elif name != "": # 判断是否按姓名查 if d['name'] == name: student_query.append(d) # 将找到的学生信息保存到列表中 show_student(student_query) # 显示查询结果 student_query.clear() # 清空列表 inputMark = input("是否继续查询?(y/n):") if inputMark == "y": mark = True else: mark = False else: print("暂未保存数据信息...") return '''3 删除学生成绩信息''' def delete(): mark = True # 标记是否循环 while mark: studentId = input("请输入要删除的学生ID:") if studentId != "": # 判断要删除的学生是否存在 if os.path.exists(filename): # 判断文件是否存在 with open(filename, 'r') as rfile: # 打开文件 student_old = rfile.readlines() # 读取全部内容 else: student_old = [] ifdel = False # 标记是否删除 if student_old: # 如果存在学生信息 with open(filename, 'w') as wfile: # 以写方式打开文件 d = {} # 定义空字典 for list in student_old: d = dict(eval(list)) # 字符串转字典 if d['id'] != studentId: wfile.write(str(d) + "\n") # 将一条学生信息写入文件 else: ifdel = True # 标记已经删除 if ifdel: print("ID为 %s 的学生信息已经被删除..." % studentId) else: print("没有找到ID为 %s 的学生信息..." % studentId) else: # 不存在学生信息 print("无学生信息...") break # 退出循环 show() # 显示全部学生信息 inputMark = input("是否继续删除?(y/n):") if inputMark == "y": mark = True # 继续删除 else: mark = False # 退出删除学生信息功能 '''4 修改学生成绩信息''' def modify(): show() # 显示全部学生信息 if os.path.exists(filename): # 判断文件是否存在 with open(filename, 'r') as rfile: # 打开文件 student_old = rfile.readlines() # 读取全部内容 else: return studentid = input("请输入要修改的学生ID:") with open(filename, "w") as wfile: # 以写模式打开文件 for student in student_old: d = dict(eval(student)) # 字符串转字典 if d["id"] == studentid: # 是否为要修改的学生 print("找到了这名学生,可以修改他的信息!") while True: # 输入要修改的信息 try: d["name"] = input("请输入姓名:") d["english"] = int(input("请输入英语成绩:")) d["python"] = int(input("请输入Python成绩:")) d["c"] = int(input("请输入C语言成绩:")) except: print("您的输入有误,请重新输入。") else: break # 跳出循环 student = str(d) # 将字典转换为字符串 wfile.write(student + "\n") # 将修改的信息写入到文件 print("修改成功!") else: wfile.write(student) # 将未修改的信息写入到文件 mark = input("是否继续修改其他学生信息?(y/n):") if mark == "y": modify() # 重新执行修改操作 '''5 排序''' def sort(): show() # 显示全部学生信息 if os.path.exists(filename): # 判断文件是否存在 with open(filename, 'r') as file: # 打开文件 student_old = file.readlines() # 读取全部内容 student_new = [] for list in student_old: d = dict(eval(list)) # 字符串转字典 student_new.append(d) # 将转换后的字典添加到列表中 else: return ascORdesc = input("请选择(0升序;1降序):") if ascORdesc == "0": # 按升序排序 ascORdescBool = False # 标记变量,为False表示升序排序 elif ascORdesc == "1": # 按降序排序 ascORdescBool = True # 标记变量,为True表示降序排序 else: print("您的输入有误,请重新输入!") sort() mode = input("请选择排序方式(1按英语成绩排序;2按Python成绩排序;3按C语言成绩排序;0按总成绩排序):") if mode == "1": # 按英语成绩排序 student_new.sort(key=lambda x: x["english"], reverse=ascORdescBool) elif mode == "2": # 按Python成绩排序 student_new.sort(key=lambda x: x["python"], reverse=ascORdescBool) elif mode == "3": # 按C语言成绩排序 student_new.sort(key=lambda x: x["c"], reverse=ascORdescBool) elif mode == "0": # 按总成绩排序 student_new.sort(key=lambda x: x["english"] + x["python"] + x["c"], reverse=ascORdescBool) else: print("您的输入有误,请重新输入!") sort() show_student(student_new) # 显示排序结果 ''' 6 统计学生总数''' def total(): if os.path.exists(filename): # 判断文件是否存在 with open(filename, 'r') as rfile: # 打开文件 student_old = rfile.readlines() # 读取全部内容 if student_old: print("一共有 %d 名学生!" % len(student_old)) else: print("还没有录入学生信息!") else: print("暂未保存数据信息...") ''' 7 显示所有学生信息 ''' def show(): student_new = [] if os.path.exists(filename): # 判断文件是否存在 with open(filename, 'r') as rfile: # 打开文件 student_old = rfile.readlines() # 读取全部内容 for list in student_old: student_new.append(eval(list)) # 将找到的学生信息保存到列表中 if student_new: show_student(student_new) else: print("暂未保存数据信息...") # 将保存在列表中的学生信息显示出来 def show_student(studentList): if not studentList: print("无数据信息 \n") return format_title = "{:^6}{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^10}" print(format_title.format("ID", "名字", "英语成绩", "Python成绩", "C语言成绩", "总成绩")) format_data = "{:^6}{:^12}\t{:^12}\t{:^12}\t{:^12}\t{:^12}" for info in studentList: print(format_data.format(info.get("id"), info.get("name"), str(info.get("english")), str(info.get("python")), str(info.get("c")), str(info.get("english") + info.get("python") + info.get("c")).center(12))) if __name__ == "__main__": main()
定义函数,给定一个列表作为函数参数,将列表中的非数字字符去除
'''定义函数,给定一个列表作为函数参数,将列表中的非数字字符去除。''' class list: def __init__(self,alist): self.alist=alist def remove_str(self): a="" for i in self.alist: b=str(i) a+=b "".join (filter(str.isdigit,a)) print("".join(filter(str.isdigit,a))) a=list([1,2,3,"q",6,"sd","[][]{"]) a.remove_str()
给定几位数,查看数根(使用函数实现)
def numRoot(num): '''定义数根函数''' if len(num) == 1: return int(num) else: nums = [] for i in range(len(num)): # 对字符串进行遍历 nums.append(int(num[i])) if sum(nums) >= 10: # 如果数值加起来大于 10 numRoot(str(sum(nums))) else: # 输出树根 print(sum(nums)) num = input("请输入一个数,查看它的数根") numRoot(num)
水果系统(面向过程,面向对象)
fruit = [] def menu(): print( ''' ********************水果超市******************** (面向对象,面向过程) 1. 查询全部水果 2. 查询指定名称的水果 3. 增加水果(增加到数据库) 4. 修改水果数量或者价格 5. 删除水果 6. 按照价格排序 7. 退出系统 *********************************************** ''' ) def showFruit(): '''功能1 查询全部水果''' print('-' * 30) print("水果的信息如下:") print('-' * 30) print('序号 水果名 价格 数量') fru_id = 1 for fru_temp in fruit: print("%s %s %s %s "%(fru_id,fru_temp['name'],fru_temp['price'],fru_temp['num'])) fru_id += 1 def searchFruitName(): '''功能2 查询指定名称的水果''' showFruit() fru_name = input("请输入想要查询的水果名称") fru_id = 1 for fru in fruit: if fru_name in fru['name']: print("该水果信息如下:") print("%d %s %s %s " % (fru_id, fru['name'], fru['price'], fru['num'])) return fru_id += 1 print("没有查询到该水果名称") def addFruit(): '''功能3 增加水果(增加到数据库)''' newFruitName = input('请输入新水果的名称') newFruitPrice = input('请输入新水果的价格') newFruitNum = input('请输入新水果的数量') newFruit = {} newFruit['name'] = newFruitName newFruit['price'] = newFruitPrice newFruit['num'] = newFruitNum fruit.append(newFruit) def changeFruit(): '''功能4 修改水果数量或者价格''' showFruit() fru_id = int(input("请输入需要修改的水果的序号: ")) changeFruitName = input('请输入修改后的水果的名称') changeFruitPrice = input('请输入修改后的水果的价格') changeFruitNum = input('请输入修改后的水果的数量') fruit[fru_id - 1]['name'] = changeFruitName fruit[fru_id - 1]['price'] = changeFruitPrice fruit[fru_id - 1]['num'] = changeFruitNum def delFruit(): '''功能5 删除水果''' showFruit() delFruitId = int(input('请输入要删除的序号:')) del fruit[delFruitId - 1] def sortFruit(): '''功能6 按照价格排序''' showFruit() sortStandard = input("请选择(0升序;1降序):") if sortStandard == "0": sortStandard = True elif sortStandard == "1": sortStandard = False else: print("您的输入有误,请重新输入!") fruit.sort(key = lambda x:x['price'],reverse = sortStandard) showFruit() def exitSystem(): '''功能7 退出系统''' print("您已经退出水果超市系统") exit() def main(): notExit = True while notExit: menu() try: option = int(input("请选择功能:")) except Exception as e: print("请重新输入") if option in [i for i in range(1,8)]: if option == 1: showFruit() elif option == 2: searchFruitName() elif option == 3: addFruit() elif option == 4: changeFruit() elif option == 5: delFruit() elif option == 6: sortFruit() elif option == 7: notExit = False exitSystem() if __name__ == '__main__': main()
class FruitMarket(): def __init__(self): self.fruit = [] def showFruit(self): '''功能1 查询全部水果''' print('-' * 30) print("水果的信息如下:") print('-' * 30) print('序号 水果名 价格 数量') fru_id = 1 for fru_temp in self.fruit: print("%s %s %s %s " % (fru_id, fru_temp['name'], fru_temp['price'], fru_temp['num'])) fru_id += 1 def searchFruitName(self): '''功能2 查询指定名称的水果''' self.showFruit() fru_name = input("请输入想要查询的水果名称") fru_id = 1 for fru in self.fruit: if fru_name in fru['name']: print("该水果信息如下:") print("%d %s %s %s " % (fru_id, fru['name'], fru['price'], fru['num'])) return fru_id += 1 print("没有查询到该水果名称") def addFruit(self): '''功能3 增加水果(增加到数据库)''' newFruitName = input('请输入新水果的名称') newFruitPrice = input('请输入新水果的价格') newFruitNum = input('请输入新水果的数量') newFruit = {} newFruit['name'] = newFruitName newFruit['price'] = newFruitPrice newFruit['num'] = newFruitNum self.fruit.append(newFruit) def changeFruit(self): '''功能4 修改水果数量或者价格''' self.showFruit() fru_id = int(input("请输入需要修改的水果的序号: ")) changeFruitName = input('请输入修改后的水果的名称') changeFruitPrice = input('请输入修改后的水果的价格') changeFruitNum = input('请输入修改后的水果的数量') self.fruit[fru_id - 1]['name'] = changeFruitName self.fruit[fru_id - 1]['price'] = changeFruitPrice self.fruit[fru_id - 1]['num'] = changeFruitNum def delFruit(self): '''功能5 删除水果''' self.showFruit() delFruitId = int(input('请输入要删除的序号:')) del self.fruit[delFruitId - 1] def sortFruit(self): '''功能6 按照价格排序''' self.showFruit() sortStandard = input("请选择(0升序;1降序):") if sortStandard == "0": sortStandard = True elif sortStandard == "1": sortStandard = False else: print("您的输入有误,请重新输入!") self.fruit.sort(key=lambda x: x['price'], reverse=sortStandard) self.showFruit() def exitSystem(self): '''功能7 退出系统''' print("您已经退出水果超市系统") exit() def menu( ): print( ''' ********************水果超市******************** (面向对象,面向过程) 1. 查询全部水果 2. 查询指定名称的水果 3. 增加水果(增加到数据库) 4. 修改水果数量或者价格 5. 删除水果 6. 按照价格排序 7. 退出系统 *********************************************** ''' ) fruitmarket = FruitMarket() def main(): notExit = True while notExit: menu() try: option = int(input("请选择功能:")) except Exception as e: print("请重新输入") if option == 1: fruitmarket.showFruit() elif option == 2: fruitmarket.searchFruitName() elif option == 3: fruitmarket.addFruit() elif option == 4: fruitmarket.changeFruit() elif option == 5: fruitmarket.delFruit() elif option == 6: fruitmarket.sortFruit() elif option == 7: notExit = False fruitmarket.exitSystem() if __name__ == '__main__': main()
matplotlib基础汇总_01
灰度化处理就是将一幅色彩图像转化为灰度图像的过程。彩色图像分为R,G,B三个分量,
分别显示出红绿蓝等各种颜色,灰度化就是使彩色的R,G,B分量相等的过程。
灰度值大的像素点比较亮(像素值最大为255,为白色),反之比较暗(像素最下为0,为黑色)。 图像灰度化的算法主要有以下3种:
data2 = data.mean(axis = 2)
data3 = np.dot(data,[0.299,0.587,0.114])
Matplotlib中的基本图表包括的元素 x轴和y轴 水平和垂直的轴线 x轴和y轴刻度 刻度标示坐标轴的分隔,包括最小刻度和最大刻度 x轴和y轴刻度标签 表示特定坐标轴的值 绘图区域 实际绘图的区域
绘制一条曲线 x = np.arange(0.0,6.0,0.01) plt.plot(x, x**2) plt.show()
绘制多条曲线 x = np.arange(1, 5,0.01) plt.plot(x, x**2) plt.plot(x, x**3.0) plt.plot(x, x*3.0) plt.show() x = np.arange(1, 5) plt.plot(x, x*1.5, x, x*3.0, x, x/3.0) plt.show()
绘制网格线 设置grid参数(参数与plot函数相同) lw代表linewidth,线的粗细 alpha表示线的明暗程度 # 使用子图显示不同网格线对比 fig = plt.figure(figsize=(20,3)) x = np.linspace(0, 5, 100) # 使用默认网格设置 ax1 = fig.add_subplot(131) ax1.plot(x, x**2, x, x**3,lw=2) ax1.grid(True) # 显式网格线 # 对网格线进行设置 ax2 = fig.add_subplot(132) ax2.plot(x, x**2, x, x**4, lw=2) ax2.grid(color='r', alpha=0.5, linestyle='dashed', linewidth=0.5) # grid函数中用与plot函数同样的参数设置网格线 # 对网格线进行设置 ax3 = fig.add_subplot(133) ax3.plot(x, x**2, x, x**4, lw=2) ax3.grid(color='r', alpha=0.5, linestyle='-.', linewidth=0.5) # grid函数中用与plot函数同样的参数设置网格线
坐标轴界限 axis 方法 x = np.arange(1, 5) plt.plot(x, x*1.5, x, x*3.0, x, x/3.0) # plt.axis() # shows the current axis limits values;如果axis方法没有任何参数,则返回当前坐标轴的上下限 # (1.0, 4.0, 0.0, 12.0) # plt.axis([0, 15, -5, 13]) # set new axes limits;axis方法中有参数,设置坐标轴的上下限;参数顺序为[xmin, xmax, ymin, ymax] plt.axis(xmax=5,ymax=23) # 可使用xmax,ymax参数 plt.show() 设置紧凑型坐标轴 x = np.arange(1, 5) plt.plot(x, x*1.5, x, x*3.0, x, x/3.0) plt.axis('tight') # 紧凑型坐标轴 plt.show() plt除了axis方法设置坐标轴范围,还可以通过xlim,ylim设置坐标轴范围 x = np.arange(1, 5) plt.plot(x, x*1.5, x, x*3.0, x, x/3.0) plt.xlim([0, 5]) # ylim([ymin, ymax]) plt.ylim([-1, 13]) # xlim([xmin, xmax]) plt.show()
坐标轴标签 plt.plot([1, 3, 2, 4]) plt.xlabel('This is the X axis') plt.ylabel('This is the Y axis') plt.show()
坐标轴标题 plt.plot([1, 3, 2, 4]) plt.title('Simple plot') plt.show()
label参数为'_nolegend_',则图例中不显示 x = np.arange(1, 5) plt.plot(x, x*1.5, label = '_nolegend_') # label参数为'_nolegend_',则图例中不显示 plt.plot(x, x*3.0, label='Fast') plt.plot(x, x/3.0, label='Slow') plt.legend() plt.show()
图例 legend legend方法 两种传参方法: 【推荐使用】在plot函数中增加label参数 在legend方法中传入字符串列表 方法一: x = np.arange(1, 5) plt.plot(x, x*1.5, label='Normal') # 在plot函数中增加label参数 plt.plot(x, x*3.0, label='Fast') plt.plot(x, x/3.0, label='Slow') plt.legend() plt.show() 方法二: x = np.arange(1, 5) plt.plot(x, x*1.5) plt.plot(x, x*3.0) plt.plot(x, x/3.0) plt.legend(['Normal', 'Fast', 'Slow']) # 在legend方法中传入字符串列表 plt.show()
loc 参数 x = np.arange(1, 5) plt.plot(x, x*1.5, label='Normal') plt.plot(x, x*3.0, label='Fast') plt.plot(x, x/3.0, label='Slow') plt.legend(loc=10) plt.show()
loc参数可以是2元素的元组,表示图例左下角的坐标 x = np.arange(1, 5) plt.plot(x, x*1.5, label='Normal') plt.plot(x, x*3.0, label='Fast') plt.plot(x, x/3.0, label='Slow') plt.legend(loc=(0,1)) # loc参数可以是2元素的元组,表示图例左下角的坐标 plt.show()
ncol参数控制图例中有几列 x = np.arange(1, 5) plt.plot(x, x*1.5, label='Normal') plt.plot(x, x*3.0, label='Fast') plt.plot(x, x/3.0, label='Slow') plt.legend(loc=0, ncol=2) # ncol控制图例中有几列 plt.show()
linestyle 属性 plt.plot(np.random.randn(1000).cumsum(), linestyle = ':',marker = '.', label='one') plt.plot(np.random.randn(1000).cumsum(), 'r--', label='two') plt.plot(np.random.randn(1000).cumsum(), 'b.', label='three') plt.legend(loc='best') # loc='best' plt.show()
保存图片 filename 含有文件路径的字符串或Python的文件型对象。图像格式由文件扩展名推断得出,例如,.pdf推断出PDF,.png推断出PNG (“png”、“pdf”、“svg”、“ps”、“eps”……) dpi 图像分辨率(每英寸点数),默认为100 facecolor 图像的背景色,默认为“w”(白色) x = np.random.randn(1000).cumsum() fig = plt.figure(figsize = (10,3)) splt = fig.add_subplot(111) splt.plot(x) fig.savefig(filename = "filena.eps",dpi = 100,facecolor = 'g')
matplotlib基础汇总_02
设置plot的风格和样式
点和线的样式
颜色 参数color或c 五种定义颜色值的方式 别名 color='r' 合法的HTML颜色名 color = 'red' HTML十六进制字符串 color = '#eeefff' 归一化到[0, 1]的RGB元组 color = (0.3, 0.3, 0.4) 灰度 color = (0.1)
透明度 y = np.arange(1, 3) plt.plot(y, c="red", alpha=0.1); # 设置透明度 plt.plot(y+1, c="red", alpha=0.5); plt.plot(y+2, c="red", alpha=0.9);
设置背景色 通过plt.subplot()方法传入facecolor参数,来设置坐标轴的背景色 plt.subplot(facecolor='orange'); plt.plot(np.random.randn(10),np.arange(1,11))
线型
不同宽度破折线 # 第一段线2个点的宽度,接下来的空白区5个点的宽度,第二段线5个点的宽度,空白区2个点的宽度,以此类推 plt.plot(np.linspace(-np.pi, np.pi, 256, endpoint=True), np.cos(np.linspace(-np.pi, np.pi, 256, endpoint=True)), dashes=[2, 5, 5, 2]);
点型 y = np.arange(1, 3, 0.2) plt.plot(y, '1', y+0.5, '2', y+1, '3', y+1.5,'4'); plt.plot(y+2, '3') #不声明marker,默认ls = None plt.plot(y+2.5,marker = '3') #声明了marker,ls 默认是实线 plt.show()
多参数连用 颜色、点型、线型 x = np.linspace(0, 5, 10) plt.plot(x,3*x,'r-.') plt.plot(x, x**2, 'b^:') # blue line with dots plt.plot(x, x**3, 'go-.') # green dashed line plt.show()
更多点和线的设置 y = np.arange(1, 3, 0.3) plt.plot(y, color='blue', linestyle='dashdot', linewidth=4, marker='o', markerfacecolor='red', markeredgecolor='black', markeredgewidth=3, markersize=12); plt.show()
在一条语句中为多个曲线进行设置 多个曲线同一设置¶ plt.plot(x1, y1, x2, y2, fmt, ...) 多个曲线不同设置¶ plt.plot(x1, y1, fmt1, x2, y2, fmt2, ...)
在一条语句中为多个曲线进行设置 多个曲线同一设置¶ plt.plot(x1, y1, x2, y2, fmt, ...) 多个曲线不同设置¶ plt.plot(x1, y1, fmt1, x2, y2, fmt2, ...)
三种设置方式 向方法传入关键字参数 对实例使用一系列的setter方法 x = np.arange(0,10) y = np.random.randint(10,30,size = 10) line,= plt.plot(x, y) line2 = plt.plot(x,y*2,x,y*3) line.set_linewidth(5) line2[1].set_marker('o') print(line,line2) 使用setp()方法 line = plt.plot(x, y) plt.setp(line, 'linewidth', 1.5,'color','r','marker','o','linestyle','--')
X、Y轴坐标刻度
xticks()和yticks()方法 x = [5, 3, 7, 2, 4, 1] plt.plot(x); plt.xticks(range(len(x)), ['a', 'b', 'c', 'd', 'e', 'f']); # 传入位置和标签参数,以修改坐标轴刻度 plt.yticks(range(1, 8, 2)); plt.show()
面向对象方法 set_xticks、set_yticks、set_xticklabels、set_yticklabels方法 fig = plt.figure(figsize=(10, 4)) ax = fig.add_subplot(111) x = np.linspace(0, 5, 100) ax.plot(x, x**2, x, x**3, lw=2) ax.set_xticks([1, 2, 3, 4, 5]) ax.set_xticklabels(['a','b','c','d','e'], fontsize=18) yticks = [0, 50, 100, 150] ax.set_yticks(yticks) ax.set_yticklabels([y for y in yticks], fontsize=18); # use LaTeX formatted labels
正弦余弦:LaTex语法,用$\pi$等表达式在图表上写上希腊字母 x = np.arange(-np.pi,np.pi,0.01) plt.figure(figsize=(12,9)) plt.plot(x,np.sin(x),x,np.cos(x)) plt.axis([x.min()-1,x.max()+1,-1.2,1.2]) #xticks:参数一刻度,参数二,对应刻度上的值 plt.xticks(np.arange(-np.pi,np.pi+1,np.pi/2), ['$-\delta$','$-\pi$/2','0','$\pi$/2','$\pi$'],size = 20) plt.yticks([-1,0,1],['min','0','max'],size = 20) plt.show()
matplotlib基础汇总_03
四图
直方图 【直方图的参数只有一个x!!!不像条形图需要传入x,y】 hist()的参数 bins 可以是一个bin数量的整数值,也可以是表示bin的一个序列。默认值为10 normed 如果值为True,直方图的值将进行归一化处理,形成概率密度,默认值为False color 指定直方图的颜色。可以是单一颜色值或颜色的序列。如果指定了多个数据集合,颜色序列将会设置为相同的顺序。如果未指定,将会使用一个默认的线条颜色 orientation 通过设置orientation为horizontal创建水平直方图。默认值为vertical x = np.random.randint(5,size = 5) display(x) plt.hist(x,histtype = 'bar'); # 默认绘制10个bin plt.show()
普通直方图/累计直方图 n = np.random.randn(10000) fig,axes = plt.subplots(1,2,figsize = (12,4)) axes[0].hist(n,bins = 50)#普通直方图 axes[0].set_title('Default histogram') axes[0].set_xlim(min(n),max(n)) axes[1].hist(n,bins = 50,cumulative = True)# 累计直方图 axes[1].set_title('Cumulative detailed histogram') axes[1].set_xlim(min(n),max(n))
正太分布 u = 100 #数学期望 s = 15 #方差 x = np.random.normal(u,s,1000) # 生成正太分布数据 ax = plt.gca() #获取当前图表 ax.set_xlabel('Value') ax.set_ylabel('Frequency') #设置x,y轴标题 ax.set_title("Histogram normal u = 100 s = 15") #设置图表标题 ax.hist(x,bins = 100,color = 'r',orientation='horizontal') plt.show()
条形图
bar # 第一个参数为条形左下角的x轴坐标,第二个参数为条形的高度; # matplotlib会自动设置条形的宽度,本例中条形宽0.8 plt.bar([1, 2, 3], [3, 2, 5]); plt.show()
# width参数设置条形宽度;color参数设置条形颜色;bottom参数设置条形底部的垂直坐标 plt.bar([1, 2, 3], [3, 2, 5], width=0.5, color='r', bottom=1); plt.ylim([0, 7]) plt.show()
# 例子:绘制并列条形图 data1 = 10*np.random.rand(5) data2 = 10*np.random.rand(5) data3 = 10*np.random.rand(5) locs = np.arange(1, len(data1)+1) width = 0.27 plt.bar(locs, data1, width=width); plt.bar(locs+width, data2, width=width, color='red'); plt.bar(locs+2*width, data3, width=width, color='green') ; plt.xticks(locs + width*1, locs); plt.show()
barh plt.barh([1, 2, 3], [3, 2, 5],height = 0.27,color = 'yellow'); plt.show()
饼图
【饼图也只有一个参数x!】 pie() 饼图适合展示各部分占总体的比例,条形图适合比较各部分的大小
plt.figure(figsize = (4,4)) # 饼图绘制正方形 x = [45,35,20] #百分比 labels = ['Cats','Dogs','Fishes'] #每个区域名称 plt.pie(x,labels = labels) plt.show()
plt.figure(figsize=(4, 4)); x = [0.1, 0.2, 0.3] # 当各部分之和小于1时,则不计算各部分占总体的比例,饼的大小是数值和1之比 labels = ['Cats', 'Dogs', 'Fishes'] plt.pie(x, labels=labels); # labels参数可以设置各区域标签 plt.show()
# labels参数设置每一块的标签;labeldistance参数设置标签距离圆心的距离(比例值) # autopct参数设置比例值的显示格式(%1.1f%%);pctdistance参数设置比例值文字距离圆心的距离 # explode参数设置每一块顶点距圆形的长度(比例值);colors参数设置每一块的颜色; # shadow参数为布尔值,设置是否绘制阴影 plt.figure(figsize=(4, 4)); x = [4, 9, 21, 55, 30, 18] labels = ['Swiss', 'Austria', 'Spain', 'Italy', 'France', 'Benelux'] explode = [0.2, 0.1, 0, 0, 0.1, 0] colors = ['r', 'k', 'b', 'm', 'c', 'g'] plt.pie(x, labels=labels, labeldistance=1.2, explode=explode, colors=colors, autopct='%1.1f%%', pctdistance=0.5, shadow=True); plt.show()
散点图
【散点图需要两个参数x,y,但此时x不是表示x轴的刻度,而是每个点的横坐标!】 scatter()
# s参数设置散点的大小;c参数设置散点的颜色;marker参数设置散点的形状 x = np.random.randn(1000) y = np.random.randn(1000) size = 50*abs(np.random.randn(1000)) colors = np.random.randint(16777215,size = 1000) li = [] for color in colors: a = hex(color) str1 = a[2:] l = len(str1) for i in range(1,7-l): str1 = '0'+str1 str1 = "#" + str1 li.append(str1) plt.scatter(x, y,s = size, c=li, marker='d'); plt.show()
import numpy as np import pandas as pd from pandas import Series,DataFrame import matplotlib.pyplot as plt x = np.random.randn(1000) y1 = np.random.randn(1000) y2 = 1.2 + np.exp(x) #exp(x) 返回的是e的x次方 ax1 = plt.subplot(121) plt.scatter(x,y1,color = 'purple',alpha = 0.3,edgecolors = 'white',label = 'no correl') plt.xlabel('no correlation') plt.grid(True) plt.legend() ax2 = plt.subplot(122) plt.scatter(x,y2,color = 'green',alpha = 0.3,edgecolors = 'gray',label = 'correl') plt.xlabel('correlation') plt.grid(True) plt.legend() plt.show()
图形内的文字、注释、箭头
文字 x = np.arange(0, 7, .01) y = np.sin(x) plt.plot(x, y); plt.text(0.1, -0.04, 'sin(0)=0'); # 位置参数是坐标 plt.show()
注释 # xy参数设置箭头指示的位置,xytext参数设置注释文字的位置 # arrowprops参数以字典的形式设置箭头的样式 # width参数设置箭头长方形部分的宽度,headlength参数设置箭头尖端的长度, # headwidth参数设置箭头尖端底部的宽度,shrink参数设置箭头顶点、尾部与指示点、注释文字的距离(比例值) y = [13, 11, 13, 12, 13, 10, 30, 12, 11, 13, 12, 12, 12, 11, 12] plt.plot(y); plt.ylim(ymax=35); # 为了让注释不会超出图的范围,需要调整y坐标轴的界限 plt.annotate('this spot must really\nmean something', xy=(6, 30), xytext=(8, 31.5), arrowprops=dict(width=15, headlength=20, headwidth=20, facecolor='black', shrink=0.1)); plt.show()
# 生成3个正态分布数据数据集 x1 = np.random.normal(30, 3, 100) x2 = np.random.normal(20, 2, 100) x3 = np.random.normal(10, 3, 100) # 绘制3个数据集,并为每个plot指定一个字符串标签 plt.plot(x1, label='plot') # 如果不想在图例中显示标签,可以将标签设置为_nolegend_ plt.plot(x2, label='2nd plot') plt.plot(x3, label='last plot') # 绘制图例 plt.legend(bbox_to_anchor=(0, 1.02, 1, 0.102), # 指定边界框起始位置为(0, 1.02),并设置宽度为1,高度为0.102 ncol=3, # 设置列数为3,默认值为1 mode="expand", # mode为None或者expand,当为expand时,图例框会扩展至整个坐标轴区域 borderaxespad=0.) # 指定坐标轴和图例边界之间的间距 # 绘制注解 plt.annotate("Important value", # 注解文本的内容 xy=(55,20), # 箭头终点所在位置 xytext=(5, 38), # 注解文本的起始位置,箭头由xytext指向xy坐标位置 arrowprops=dict(arrowstyle='->')); # arrowprops字典定义箭头属性,此处用arrowstyle定义箭头风格
箭头
matplotlib基础汇总_04
3D图形
导包 import numpy as np import matplotlib.pyplot as plt #3d图形必须的 from mpl_toolkits.mplot3d.axes3d import Axes3D %matplotlib inline
生成数据 #系数,由X,Y生成Z a = 0.7 b = np.pi #计算Z轴的值 def mk_Z(X, Y): return 2 + a - 2 * np.cos(X) * np.cos(Y) - a * np.cos(b - 2*X) #生成X,Y,Z x = np.linspace(0, 2*np.pi, 100) y = np.linspace(0, 2*np.pi, 100) X,Y = np.meshgrid(x, y) Z = mk_Z(X, Y)
绘制图形 fig = plt.figure(figsize=(14,6)) #创建3d的视图,使用属性projection ax = fig.add_subplot(1, 2, 1, projection='3d') ax.plot_surface(X,Y,Z,rstride = 5,cstride = 5) #创建3d视图,使用colorbar,添加颜色柱 ax = fig.add_subplot(1, 2, 2, projection='3d') p = ax.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap='rainbow', antialiased=True) cb = fig.colorbar(p, shrink=0.5)
玫瑰图
#极坐标条形图 def showRose(values,title): max_value = values.max() # 分为8个面元 N = 8 # 面元的分隔角度 angle = np.arange(0.,2 * np.pi, 2 * np.pi / N) # 每个面元的大小(半径) radius = np.array(values) # 设置极坐标条形图 plt.axes([0, 0, 2, 2], polar=True,facecolor = 'g') colors = [(1 - x/max_value, 1 - x/max_value, 0.75) for x in radius] # 画图 plt.bar(angle, radius, width=(2*np.pi/N), bottom=0.0, color=colors) plt.title(title,x=0.2, fontsize=20)
绘制图形 #拉韦纳(Ravenna)又译“腊万纳”“拉文纳”“拉温拿”。意大利北部城市。位于距亚得里亚海10公里的沿海平原上 data = np.load('Ravenna_wind.npy') hist, angle = np.histogram(data,8,[0,360]) showRose(hist,'Ravenna')
城市气候与海洋关系
导包 import numpy as np import pandas as pd import matplotlib.pyplot as plt from pandas import Series,DataFrame %matplotlib inline
加载数据 #意大利小镇费拉拉 ferrara1 = pd.read_csv('./ferrara_150715.csv') ferrara2 = pd.read_csv('./ferrara_250715.csv') ferrara3 = pd.read_csv('./ferrara_270615.csv') ferrara = pd.concat([ferrara1,ferrara2,ferrara3],ignore_index=True)
去除没用的列 asti.drop(['Unnamed: 0'],axis = 1,inplace=True) bologna.drop(['Unnamed: 0'],axis = 1,inplace=True) cesena.drop(['Unnamed: 0'],axis = 1,inplace=True) ferrara.drop(['Unnamed: 0'],axis = 1,inplace=True) mantova.drop(['Unnamed: 0'],axis = 1,inplace=True) milano.drop(['Unnamed: 0'],axis = 1,inplace=True) piacenza.drop(['Unnamed: 0'],axis = 1,inplace=True) ravenna.drop(['Unnamed: 0'],axis = 1,inplace=True) torino.drop(['Unnamed: 0'],axis = 1,inplace=True)
获取个城市距离海边距离,最高温度,最低温度,最高湿度,最低湿度 dist = [ravenna['dist'][0], cesena['dist'][0], faenza['dist'][0], ferrara['dist'][0], bologna['dist'][0], mantova['dist'][0], piacenza['dist'][0], milano['dist'][0], asti['dist'][0], torino['dist'][0] ] temp_max = [ravenna['temp'].max(), cesena['temp'].max(), faenza['temp'].max(), ferrara['temp'].max(), bologna['temp'].max(), mantova['temp'].max(), piacenza['temp'].max(), milano['temp'].max(), asti['temp'].max(), torino['temp'].max() ] temp_min = [ravenna['temp'].min(), cesena['temp'].min(), faenza['temp'].min(), ferrara['temp'].min(), bologna['temp'].min(), mantova['temp'].min(), piacenza['temp'].min(), milano['temp'].min(), asti['temp'].min(), torino['temp'].min() ] hum_min = [ravenna['humidity'].min(), cesena['humidity'].min(), faenza['humidity'].min(), ferrara['humidity'].min(), bologna['humidity'].min(), mantova['humidity'].min(), piacenza['humidity'].min(), milano['humidity'].min(), asti['humidity'].min(), torino['humidity'].min() ] hum_max = [ravenna['humidity'].max(), cesena['humidity'].max(), faenza['humidity'].max(), ferrara['humidity'].max(), bologna['humidity'].max(), mantova['humidity'].max(), piacenza['humidity'].max(), milano['humidity'].max(), asti['humidity'].max(), torino['humidity'].max() ]
显示最高温度与离海远近的关系 plt.axis([0,400,32,35]) plt.plot(dist,temp_max,'ro')
根据距海远近划分数据 观察发现,离海近的可以形成一条直线,离海远的也能形成一条直线。 首先使用numpy:把列表转换为numpy数组,用于后续计算。 分别以100公里和50公里为分界点,划分为离海近和离海远的两组数据 # 把列表转换为numpy数组 x = np.array(dist) display('x:',x) y = np.array(temp_max) display('y:',y) # 离海近的一组数据 x1 = x[x<100] x1 = x1.reshape((x1.size,1)) display('x1:',x1) y1 = y[x<100] display('y1:',y1) # 离海远的一组数据 x2 = x[x>50] x2 = x2.reshape((x2.size,1)) display('x2:',x2) y2 = y[x>50] display('y2:',y2)
机器学习计算回归模型 from sklearn.svm import SVR svr_lin1 = SVR(kernel='linear', C=1e3) svr_lin2 = SVR(kernel='linear', C=1e3) svr_lin1.fit(x1, y1) svr_lin2.fit(x2, y2) xp1 = np.arange(10,100,10).reshape((9,1)) xp2 = np.arange(50,400,50).reshape((7,1)) yp1 = svr_lin1.predict(xp1) yp2 = svr_lin2.predict(xp2)
绘制回归曲线 plt.plot(xp1, yp1, c='r', label='Strong sea effect') plt.plot(xp2, yp2, c='b', label='Light sea effect') #plt.axis('tight') plt.legend() plt.scatter(x, y, c='k', label='data')
最低温度与海洋距离关系 plt.axis((0,400,16,21)) plt.plot(dist,temp_min,'bo')
最低湿度与海洋距离关系 plt.axis([0,400,70,120]) plt.plot(dist,hum_min,'bo')
最高湿度与海洋距离关系 plt.axis([0,400,70,120]) plt.plot(dist,hum_max,'bo')
平均湿度与海洋距离的关系 hum_mean = [ravenna['humidity'].mean(), cesena['humidity'].mean(), faenza['humidity'].mean(), ferrara['humidity'].mean(), bologna['humidity'].mean(), mantova['humidity'].mean(), piacenza['humidity'].mean(), milano['humidity'].mean(), asti['humidity'].mean(), torino['humidity'].mean() ] plt.plot(dist,hum_mean,'bo')
风速与风向的关系 plt.plot(ravenna['wind_deg'],ravenna['wind_speed'],'ro')
在子图中,同时比较风向与湿度和风力的关系 plt.subplot(211) plt.plot(cesena['wind_deg'],cesena['humidity'],'bo') plt.subplot(212) plt.plot(cesena['wind_deg'],cesena['wind_speed'],'bo')
玫瑰图 def showRoseWind(values,city_name): ''' 查看风向图,半径越大,代表这个方向上的风越多 ''' max_value = values.max() # 分为8个面元 N = 8 # 面元的分隔角度 theta = np.arange(0.,2 * np.pi, 2 * np.pi / N) # 每个面元的大小(半径) radii = np.array(values) # 设置极坐标条形图 plt.axes([0.025, 0.025, 0.95, 0.95], polar=True) colors = [(1 - x/max_value, 1 - x/max_value, 0.75) for x in radii] # 画图 plt.bar(theta, radii, width=(2*np.pi/N), bottom=0.0, color=colors) plt.title(city_name,x=0.2, fontsize=20)
用numpy创建一个直方图,将360度划分为8个面元,将数据分类到这8个面元中 hist, bin = np.histogram(ravenna['wind_deg'],8,[0,360]) print(hist) hist = hist/hist.sum() print(bin) showRoseWind(hist,'Ravenna')
计算米兰各个方向的风速 print(milano[milano['wind_deg']<45]['wind_speed'].mean()) print(milano[(milano['wind_deg']>44) & (milano['wind_deg']<90)]['wind_speed'].mean()) print(milano[(milano['wind_deg']>89) & (milano['wind_deg']<135)]['wind_speed'].mean()) print(milano[(milano['wind_deg']>134) & (milano['wind_deg']<180)]['wind_speed'].mean()) print(milano[(milano['wind_deg']>179) & (milano['wind_deg']<225)]['wind_speed'].mean()) print(milano[(milano['wind_deg']>224) & (milano['wind_deg']<270)]['wind_speed'].mean()) print(milano[(milano['wind_deg']>269) & (milano['wind_deg']<315)]['wind_speed'].mean()) print(milano[milano['wind_deg']>314]['wind_speed'].mean())
将各个方向风速保存到列表中 degs = np.arange(45,361,45) tmp = [] for deg in degs: tmp.append(milano[(milano['wind_deg']>(deg-46)) & (milano['wind_deg']<deg)]['wind_speed'].mean()) speeds = np.array(tmp) print(speeds)
画出各个方向的风速 N = 8 theta = np.arange(0.,2 * np.pi, 2 * np.pi / N) radii = np.array(speeds) plt.axes([0.025, 0.025, 0.95, 0.95], polar=True) colors = [(1-x/10.0, 1-x/10.0, 0.75) for x in radii] bars = plt.bar(theta, radii, width=(2*np.pi/N), bottom=0.0, color=colors) plt.title('Milano',x=0.2, fontsize=20)
抽取函数 def RoseWind_Speed(city): degs = np.arange(45,361,45) tmp = [] for deg in degs: tmp.append(city[(city['wind_deg']>(deg-46)) & (city['wind_deg']<deg)]['wind_speed'].mean()) return np.array(tmp) def showRoseWind_Speed(speeds,city_name): N = 8 theta = np.arange(0.,2 * np.pi, 2 * np.pi / N) radii = np.array(speeds) plt.axes([0.025, 0.025, 0.95, 0.95], polar=True) colors = [(1-x/10.0, 1-x/10.0, 0.75) for x in radii] bars = plt.bar(theta, radii, width=(2*np.pi/N), bottom=0.0, color=colors) plt.title(city_name,x=0.2, fontsize=20)
函数调用 showRoseWind_Speed(RoseWind_Speed(ravenna),'Ravenna')
根据列表的值来显示每一个元素出现的次数
lst = ['中雨','雷阵雨','中到大雨','阴','多云','晴','中雨'] dic = {} for i in lst: if i not in dic: dic[i] = lst.count(i) print(dic)
钻石和玻璃球游戏(钻石位置固定)
''' 开始,你可以随意选择一个抽屉,在开启它之前, 主持人会开启另外一个抽屉,露出抽屉里的玻璃球。 这时,主持人会给你一次更换自己选择的机会。 请自己认真分析一下“不换选择能有更高的几率获得钻石, 还是换选择能有更高的几率获得钻石?或几率没有发生变化?”写出你分析的思路和结果。 设法编写python程序验证自己的想法, 验证的结果支持了你的分析结果,还是没有支持你的分析结果, 请写出结果,并附上你的程序代码,并在程序代码中通过注释说明你解决问题的思路。 (提示:可以借助随机数函数完成此程序) ''' import random print("钻石和玻璃球的游戏开始了") # 摆在你面前有3个关闭的抽屉 lst_dic = [{'抽屉':'钻石'},{'抽屉':'玻璃球'},{'抽屉':'玻璃球'}] # 定义钻石 zs = 0 # 定义玻璃球 blq = 0 def Game(your_choice,lst_dic): isLouchu = False # 查看主持人是否露出 for num in range(len(lst_dic)): if not isLouchu: if lst_dic[your_choice]['抽屉'] == '钻石': # 第一种 抽到 钻石 if num != your_choice: print("主持人露出了 %d 号抽屉的玻璃球"%(num + 1)) isLouchu = True else: # 第二种 抽到 玻璃球 if num != your_choice and lst_dic[num]['抽屉'] != '钻石': print("主持人露出了 %d 号抽屉的玻璃球"%(num + 1)) isLouchu = True choice = 'yn' you_select = random.choice(choice) if you_select == 'y': lst_nums = [0,1,2] ischoose = False for new_choice in lst_nums: if not ischoose : if (new_choice != num) and (new_choice != your_choice): print("你新的选择是:",new_choice+1,"号抽屉") your_choice = new_choice ischoose = True ChooseLater(your_choice) else: print("不变选择,继续坚持我的 %d 号抽屉"%(your_choice + 1)) your_choice = your_choice ChooseLater(your_choice) def ChooseLater(your_choice): # 选择后进行计数 公布答案 global zs, blq if lst_dic[your_choice]['抽屉'] == '钻石': zs += 1 # 钻石数 +1 else: blq += 1 # 玻璃球数 +1 answer_num = 0 isanswer = False for answer in lst_dic: if not isanswer: if answer['抽屉'] == '钻石': print("钻石在 %d 号抽屉 "%(answer_num + 1)) isanswer = True answer_num += 1 nums = int(input("请输入想要实验的次数")) for i in range(nums): # 你可以随意选择一个抽屉 your_choice = random.randint(0, 2) print("你当前想要选择的是 %d 号抽屉" % (your_choice + 1)) Game(your_choice,lst_dic) print("抽到的钻石数为: %d"%(zs)) print("抽到的玻璃球数为: %d"%(blq)) print("钻石的概率是 %.2f"%(zs/nums))
小人推心图(网上代码)
from turtle import * def go_to(x, y): up() goto(x, y) down() def head(x, y, r): go_to(x, y) speed(1) circle(r) leg(x, y) def leg(x, y): right(90) forward(180) right(30) forward(100) left(120) go_to(x, y - 180) forward(100) right(120) forward(100) left(120) hand(x, y) def hand(x, y): go_to(x, y - 60) forward(100) left(60) forward(100) go_to(x, y - 90) right(60) forward(100) right(60) forward(100) left(60) eye(x, y) def eye(x, y): go_to(x - 50, y + 130) right(90) forward(50) go_to(x + 40, y + 130) forward(50) left(90) def big_Circle(size): speed(20) for i in range(150): forward(size) right(0.3) def line(size): speed(1) forward(51 * size) def small_Circle(size): speed(10) for i in range(210): forward(size) right(0.786) def heart(x, y, size): go_to(x, y) left(150) begin_fill() line(size) big_Circle(size) small_Circle(size) left(120) small_Circle(size) big_Circle(size) line(size) end_fill() def main(): pensize(2) color('red', 'pink') head(-120, 100, 100) heart(250, -80, 1) go_to(200, -300) write("To: Hany", move=True, align="left", font=("楷体", 20, "normal")) done() main()
0525习题
for i in range(1000,2201): if i % 7 == 0 and i % 5 != 0: print(i,end = " ") def func(num): if num == 0: return 1 return num * func(num - 1) print(func(5))
for i in range(100,1000): a = i//100 b = i//10 % 10 c = i%100%10 if a**3 + b**3 + c**3 == i: print(i)
name = 'seven' passwd = '123' num = 3 while num: input_name = input("请输入用户名") input_passwd = input("请输入密码") if input_name == name and input_passwd == passwd: print("登陆成功") break else: print("登陆失败") num = num - 1
x,y=eval(input("请输入两个数字,逗号分隔:")) lst_num=[] for i in range(x): L=[] for j in range(y): L.append(j*i) lst_num.append(L) print(lst_num)
def rank(score): if isinstance(score,int): if 90 <= score <= 100: print("优秀") elif 80<= score <= 89: print("良好") elif 60<= score <= 79: print("及格") elif 0<= score <= 59: print("不及格") else: print("输入有误!") try: score = eval(input("请输入一个学生的成绩")) rank(score) except Exception as e: print("请输入数字")
def test(name): if name == 'exit': print('欢迎下次使用') if name[0].isalpha() or name[0] == '_': for i in name[1:]: if not (i.isalnum() or i == '_'): print('变量名不合法') break else: print('变量名合法!') else: print('变量名非法!') name = input() test(name)
def comb(n,m): if(n == m or (not m)): return 1 else: return comb(n-1,m) + comb(n-1,m-1) try: n,m = eval(input()) print(comb(n,m)) except : print("输入有误!")
def sort(dct): newDct={} items = list(dct.items()) items.sort(key=lambda x:x[1],reverse=True) for i in range(len(dct)): name,score = items[i] newDct[name] = score print("第%d名:%s,成绩: %.2f分"%(i+1,name,newDct[name])) def avg(dct): scores = list(dct.values()) print("最高分:%.2f"%(max(scores)),end = "") print("最低分:%.2f" % (min(scores)),end="") print("平均分:%.2f" % (sum(scores) / len(scores)),end="") dct={} dct['张三'],dct['李四'],dct['王五'],dct['赵六'],dct['侯七']=eval(input()) sort(dct) avg(dct)
words = "Python" print("{:#^9}".format(words))
string = "Python" if "p" in string: print(string[:-1]) else: print(string[0:4])
# 创建文件data.txt,共100000行,每行存放一个1~100之间的整数 import random f = open('data.txt','w+') for i in range(100000): f.write(str(random.randint(1,100)) + '\n') f.seek(0,0) print(f.read()) f.close()
# 生成100个MAC地址并写入文件中,MAC地址前6位(16进制)为01-AF-3B # 01-AF-3B(-xx)(-xx)(-xx) # -xx # 01-AF-3B-xx # -xx # 01-AF-3B-xx-xx # -xx # 01-AF-3B-xx-xx-xx import random import string def create_mac(): mac = '01-AF-3B' # 生成16进制的数 hex_num = string.hexdigits for i in range(3): # 从16进制字符串中随机选择两个数字 # 返回值是一个列表 n = random.sample(hex_num,2) # 拼接内容 将小写字母转换称大写字母 sn = '-' + ''.join(n).upper() mac += sn return mac # 主函数 随机生成100个mac地址 def main(): with open('mac.txt','w') as f: for i in range(100): mac = create_mac() print(mac) f.write(mac + '\n') main()
# 生成一个大文件ips.txt,要求1200行,每行随机为172.25.254.0/24段的ip # 读取ips.txt文件统计这个文件中ip出现频率排前10的ip import random def create_ip(filename): ip=['172.25.254.'+str(i) for i in range(1,255)] with open(filename,'w') as f: for i in range(1200): f.write(random.sample(ip,1)[0]+'\n') create_ip('ips.txt') ips_dict={} with open('ips.txt') as f : for ip in f: ip=ip.strip() if ip in ips_dict: ips_dict[ip]+=1 else: ips_dict[ip]=1 sorted_ip=sorted(ips_dict.items(),key=lambda x:x[1],reverse=True)[:10] print(sorted_ip)
jieba尝鲜
import jieba strings = '我工作在安徽的安徽师范大学,这个大学很美丽,在芜湖' # print(dir(jieba)) dic_strings = {} lst_strings = jieba.lcut(strings) for ci in lst_strings: # 对得到的分词进行汇总 dic_strings[ci] = lst_strings.count(ci) # 更改字典中单词出现的次数 print(dic_strings)
inf 无穷 inf = float('inf')
读取文件进行绘图
import numpy as np import pandas as pd import matplotlib.pyplot as plt cqlq=pd.read_csv("cqlq.txt",sep="\s+",encoding="gbk") dxnt=pd.read_csv("dxnt.txt",sep="\s+",encoding="gbk") ggdq=pd.read_csv("ggdq.txt",sep="\s+",encoding="gbk") giyy=pd.read_csv("gjyy.txt",sep="\s+",encoding="gbk") cqlq.columns = ["date","oppr","hipr","lopr","clpr","TR"] dxnt.columns = ["date","oppr","hipr","lopr","clpr"] ggdq.columns = ["date","oppr","hipr","lopr","clpr","TR"] giyy.columns = ["date","oppr","hipr","lopr","clpr","TR"] a=cqlq b=dxnt c=ggdq d=giyy ua=(a["clpr"]-a["clpr"].shift(1))/a["clpr"] ub=(b["clpr"]-b["clpr"].shift(1))/b["clpr"] uc=(c["clpr"]-c["clpr"].shift(1))/c["clpr"] ud=(d["clpr"]-d["clpr"].shift(1))/d["clpr"] u=pd.concat([ua,ub,uc,ud],axis=1) u.dropna() miu=u.mean()+0.005 jz=u.cov() yi = np.ones(4) miu= np.mat(miu) jz = np.mat(jz) yi = np.mat(yi) nijz = jz.I a = miu*nijz*miu.T b =yi*nijz*miu.T c = yi*nijz*yi.T deta=a*c-b**2 stock_y=[i*0.0001 for i in range(100)] stock_x=[(np.sqrt(( c/deta)*(rp-b/c)**2+1/c)).max() for rp in stock_y] plt.rcParams['font.sans-serif']=['SimHei'] plt.plot(stock_x,stock_y) plt.xlabel("方差") plt.ylabel("期望") print(miu) print(jz) plt.show()
Sqlite3 实现学生信息增删改查 import sqlite3 conn = sqlite3.connect('studentsdb.db') # 连接数据库 cursor = conn.cursor( ) # 创建数据表 def createDatabase(): '''创建一个数据表''' sql = 'create table student(stuId int primary key,stuName text,stuAge text,stuGender text,stuClass text)' cursor.execute(sql) conn.commit() def addInfo(sql = ''): '''添加数据''' if sql =='': # 如果是初始化,则默认会进行增加 6 条数据 stuInfo = [(1001, '小华', '20', '男', '二班'), (1002, '小明', '19', '女', '二班'), (1003, '小李', '20', '女', '一班'), (1004, '小王', '18', '男', '一班'), (1005, '小刘', '20', '女', '二班'), (1006, '小张', '19', '女', '一班')] cursor.executemany("insert into student values(?,?,?,?,?)",stuInfo) # 插入多条语句 conn.commit() def deleteInfo(): '''删除数据''' cursor.execute("delete from student where stuId = 1005") # 将学号为 1005 的小刘同学删除 conn.commit() def modifyInfo(): '''修改数据''' sql = "update student set stuAge = ? where stuId = ?" cursor.execute(sql,(20,1006)) # 将小张的年龄修改为 20 conn.commit() def selectInfo(): '''查询学生信息''' sql = 'select * from student' # 查询全部数据 cursor.execute(sql) print(cursor.fetchall()) def main(): # 创建一个数据表 createDatabase() # 添加数据 print("添加六条学生数据之后") addInfo() selectInfo() # 修改数据 print("将小张的年龄修改为 20") modifyInfo() selectInfo() # 删除数据 print("将学号为 1005 的小刘同学删除") deleteInfo() selectInfo() # cursor.execute('drop table student') # conn.commit() main()
绘图 示例
import numpy as np import pandas as pd import matplotlib.pyplot as plt cqlq=pd.read_csv("cqlq.txt",sep="\s+",encoding="gbk") dxnt=pd.read_csv("dxnt.txt",sep="\s+",encoding="gbk") ggdq=pd.read_csv("ggdq.txt",sep="\s+",encoding="gbk") giyy=pd.read_csv("gjyy.txt",sep="\s+",encoding="gbk") cqlq.columns = ["date","oppr","hipr","lopr","clpr","TR"] dxnt.columns = ["date","oppr","hipr","lopr","clpr"] ggdq.columns = ["date","oppr","hipr","lopr","clpr","TR"] giyy.columns = ["date","oppr","hipr","lopr","clpr","TR"] a=cqlq b=dxnt c=ggdq d=giyy ua=(a["clpr"]-a["clpr"].shift(1))/a["clpr"] ub=(b["clpr"]-b["clpr"].shift(1))/b["clpr"] uc=(c["clpr"]-c["clpr"].shift(1))/c["clpr"] ud=(d["clpr"]-d["clpr"].shift(1))/d["clpr"] u=pd.concat([ua,ub,uc,ud],axis=1) u.dropna() miu=u.mean()+0.005 jz=u.cov() yi = np.ones(4) miu= np.mat(miu) jz = np.mat(jz) yi = np.mat(yi) nijz = jz.I a = miu*nijz*miu.T b =yi*nijz*miu.T c = yi*nijz*yi.T deta=a*c-b**2 stock_y=[i*0.0001 for i in range(100)] stock_x=[(np.sqrt(( c/deta)*(rp-b/c)**2+1/c)).max() for rp in stock_y] plt.rcParams['font.sans-serif']=['SimHei'] plt.plot(stock_x,stock_y) plt.xlabel("方差") plt.ylabel("期望") print(miu) print(jz) plt.show()
使用正则匹配数字
import re pattern = '\d+?\.\d+' s = "[Decimal('90.900000')]" s2 = "[Decimal('75.900000'),Decimal('57.280000')]" [print(i,end = " ") for i in re.findall(pattern,s)] print() [print(i,end = " ") for i in re.findall(pattern,s2)]
0528习题
''' 1. 编写程序实现:计算并输出标准输入的三个数中绝对值最小的数。 ''' #计算并输出标准输入的三个数中绝对值最小的数。 import math num1 = int(input()) num2 = int(input()) num3 = int(input()) num_list = (num1, num2, num3) index_min = 0 #绝对值最小的元素的下标 if math.fabs(num_list[index_min]) > math.fabs(num_list[1]): index_min = 1 if math.fabs(num_list[index_min]) > math.fabs(num_list[2]): index_min = 2 for n in num_list: if math.fabs(num_list[index_min]) == math.fabs(n): print(n, end=' ')
''' 2. 编写程序,功能是输入五分制成绩, 输出对应的百分制分数档。 不考虑非法输入的情形。 对应关系为:A: 90~100, B: 80~89, C: 70~79,D: 60~69, E: 0~59 ''' score = int(input()) if 90 <= score <= 100: print("A") elif 80 <= score <= 89: print("B") elif 70 <= score <= 79: print("C") elif 60 <= score <= 69: print("D") elif 0 <= score <= 59: print("E") else: print("请输入正确分数")
''' 3. 编写程序, 输入年(year)、月(month),输出该年份该月的天数。 公历闰年的计算方法为:年份能被4整除且不能被100整除的为闰年; 或者,年份能被400整除的是闰年。 ''' year = int(input("请输入年份")) month = int(input("请输入月份")) month_lst = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if (year %4 == 0 and year % 100 !=0) and year % 400 == 0: month_lst[1] = 29 print(month_lst[month - 1])
''' 4. 编写程序,功能是输入一个数,输出该数的绝对值 ''' num = int(input()) print(abs(num))
''' 5. 编写“猜数游戏”程序, 功能是: 如果用户输入的数等于程序选定的数(该数设定为10),则输出“you win”, 否则如果大于选定的数,则输出“too big”,反之输出“too small”。 ''' num = 10 your_num = int(input()) if your_num == num: print("you win") elif your_num > num: print("too big") else: print("too small")
关于某一爬虫实例的总结
os.chdir(r"C:\Users\47311\Desktop\code\") #修改为自己文件路径
data = pd.read_excel(r"公司公告2020.xlsx")[:-1] #读入数据,并删除最后一行(最后一行为空值)
读取的数据在 chdir 之下
存在多个数据时,使用字符串类型进行 split 分割 " 可能会出错,需要异常处理
DataFrame 对象.apply(函数名) 经常会使用,可以用来赋值新的值 def address(str): #定义提取公告地址函数 try: return str.split('"')[1] except: pass data["公告地址"] = data["公告地址"].apply(address)
对代码进行获取某一个值时 可以先获取数据上面的内容 html = requests.get(url).text 使用 etree.HTML(html) 进行解析 使用 xpath 读取路径 tree.xpath("xxxx") 返回读取到的内容,对原内容进行更新 return "http://xxxx.com/" + url[0]
data.iterrows() 读取每一行的数据 for index, row in data.iterrows(): row['属性'] 进行获取值 添加文件后缀 name = row['公告标题'].split(':')[0] + row["证券代码"][:6] + "_" + row["公告日期"] + ".pdf"
爬取时,进行必要的条件信息的说明 使用 urlretrieve(url,filename = r' xxx ') 进行保存
当获取到的数据不存在时,可以通过设置一个 len( data ) 设置一个长度 ,过滤掉 不到长度的数据 设置一个布尔类型的全局变量 当访问到时 设置为 True 如果没有访问到,则设置为 False 根据全局变量的值,判断是否继续进行访问
是否感染病毒
import random ganran = float(input("请输入感染概率")) is_person_ganran = False # 人是否感染了 person_ganran = random.randint(0,100) if person_ganran /100 < ganran: is_person_ganran = True print(person_ganran) if is_person_ganran: print("被感染了") else: print("还是正常人")
python文件操作 file = open('abc.txt','r',encoding='utf-8') file = open('abc.txt','w',encoding='utf-8') 'w' 写入模式 会清空掉文件,然后再写入 不想完全覆盖掉原文件的话,使用'a' 关键字with,with open(xxx) as f 避免打开文件后忘记关闭 readline() 读取一行 读取出来的数据 后面都有\n readlines() 将每一行形成一个元素,放到一个列表中 seek操作 seek(n)光标移动到n位置 注意: 移动单位是byte 如果是utf-8的中文部分要是3的倍数 seek(0,0)默认为0,移动到文件头 seek(0,1)移动到当前位置 seek(0,2)移动到文件尾 tell() 获取当前光标在什么位置 修改文件 将文件中的内容读取到内存中 将信息修改完毕, 然后将源文件删除, 将新文件的名字改成原来文件的名字 可以一行一行的读取修改,避免溢出
pandas 几个重要知识点
将 NaN 替换成某一数值 使用 fillna dataframe.fillna(value = 'xxx',inplace=True) 删除某一个值 使用 drop dataframe.drop(10,inplace=True) 交换两行的值 if m != n: temp = np.copy(dataframe[m]) dataframe[m] = dataframe[n] dataframe[n] = temp else: temp = np.copy(dataframe[dataframe.shape[1]-1]) dataframe[dataframe.shape[1]-1] = dataframe[n] dataframe[n] = temp 删除 columns 这些列 dataframe.drop(columns = list, inplace=True)
一千美元的故事(钱放入信封中)
def dollar(n): global story_money money = [] for i in range(10): if 2**(i+1) > story_money-sum(money): money.append(story_money-2**i+1) break money.append(2 ** i) # print(money) answer = [] if n >= money[-1]: answer.append(10) n -= money[-1] n = list(bin(n))[2:] n.reverse() rank = 1 for i in n: if i == '1': answer.append(rank) rank += 1 print(answer) story_money = 1000 dollar(500)
给定两个列表,转换为DataFrame类型
import pandas as pd def get_data(): q1 = [] q2 = [] p1 = input("list 1:") p2 = input("list 2:") q1=p1.split(',') q2=p2.split(',') for i,j in zip(range(len(q1)),range(len(q2))): q1[i] = int(q1[i])**1 q2[j] = float(q2[j])**2 dic = { "L":q1, "I":q2 } A = pd.DataFrame(dic) print(A) get_data() 1.将输入的使用 split(',') 进行分割 2.使用 for i,j in zip(range(len(q1)),range(len(q2))) 对 q1 和 q2 都进行遍历 3.使用字典,将列表作为值,传递过去 使用 pd.DataFrame 进行转换
通过文档算学生的平均分
tom 85 90 jerry 95 80 lucy 80 90 rose 88 90 jay 76 75 summer 87 85 horry 84 80
dic = {} with open('score.txt','r') as f: lines = f.readlines() f.close() for line in lines: line = line.strip('\n').split(' ') dic[line[0]] = (int(line[1]),int(line[2])) name = input() if name not in dic.keys(): print("not found") else: print(sum(dic[name])/len(dic[name]))
0528习题 11-15
''' 6. 一元二次方程:ax2+bx+c=0 (a ╪ 0) 【输入形式】输入a、b和c的值(有理数) 【输出形式】输出x的两个值,或者No(即没有有理数的解) ''' import math a = int(input()) b = int(input()) c = int(input()) disc = b*b - 4*a*c p = -b/(2*a) if disc > 0: q = math.sqrt(disc)/(2*a) x1 = p + q x2 = p - q print("x1 = %s,x2 = %s"%(str(x1,x2))) elif disc == 0: x1 = p print("x1 = x2 = ",x1) else: disc = -disc q = math.sqrt(disc)/(2*a) print("x1 = ",p,"+",q) print("x2 = ", p, "-", q)
''' 7. 计算1+1/2+1/3+...+1/n ''' n = int(input()) sum = 0 for i in range(1,n+1): sum += 1/i print(sum)
''' 8. 编写猜数游戏程序,功能是:允许用户反复输入数, 直至猜中程序选定的数(假定为100)。 输入的数如果大于选定的数,则提示"larger than expected"; 如果小于选定的数,则提示"less than expected"; 如果等于选定的数,则输出"you win"并结束程序。 ''' import random num = random.randint(1,5) while True: your_num = int(input()) if your_num == num: print("you win") break elif your_num > num: print("larger than expected") else: print("less than expected")
''' 9. 计算1-100之间的偶数和 ''' num_lst = [i for i in range(1,101) if i % 2 == 0] print(sum(num_lst))
''' 10. 猴子摘下若干个桃子,第一天吃了桃子的一半多一个, 以后每天吃了前一天剩下的一半多一个, 到第n天吃以前发现只剩下一个桃子, 编写程序实现:据输入的天数计算并输出猴子共摘了几个桃子 【输入形式】输入的一行为一个非负整数,表示一共吃的天数。 【输出形式】输出的一行为一个非负整数,表示共摘了几个桃子, 若输入的数据不合法(如:负数或小数),则输出"illegal data"。 ''' def Peach(day,yesterday_sum,now_rest): if day != 0: day -= 1 yesterday_sum = (now_rest + 1) * 2 now_rest = yesterday_sum return Peach(day,yesterday_sum,now_rest) else: return yesterday_sum yesterday_sum = 0 now_rest = 1 day = int(input()) if day <= 0: print("illegal data") exit() print(Peach(day,yesterday_sum,now_rest))
0528习题 6-10
''' 1. 编写程序,功能是把输入的字符串的大写字母变成小写字母, 小写字母变成大写字母,非字母的字符不作变换。输出变换后的结果 ''' string = input() s = '' for str in string: if 'a' <= str <= 'z': s += str.upper() elif 'A' <= str <= 'Z': s += str.lower() else: s += str print(s) ''' 2. 已知10个四位数输出所有对称数及个数 n, 例如1221、2332都是对称数。 【输入形式】10个四位数,以空格分隔开 【输出形式】输入的四位数中的所有对称数,对称数个数 ''' input_nums = input().split() nums = [] for num in input_nums: nums.append(int(num)) symmetric_num = [] for num in nums: num = str(num) if num[0] == num[3] and num[1] == num[2]: symmetric_num.append(num) print("对称数:") [print(i,end = " ") for i in symmetric_num] print(len(symmetric_num)) # 1221 2243 2332 1435 1236 5623 4321 4356 6754 3234 ''' 学校举办新生歌手大赛,每个选手的成绩 由评委的评分去掉一个最高分和一个最低分剩下评分的平均值得到。 编写程序实现:输入第一行指定n,从第二行开始每行输入一个评委的得分(共n行), 计算选手的成绩,并输出。 ''' n = int(input()) player = [] for i in range(n): score = float(input()) player.append(score) player.remove(max(player)) player.remove(min(player)) print("%.1f"%(sum(player)/len(player))) ''' 1. 编写程序实现:计算并输出标准输入的三个数中绝对值最小的数。 ''' #计算并输出标准输入的三个数中绝对值最小的数。 import math num1 = int(input()) num2 = int(input()) num3 = int(input()) num_list = (num1, num2, num3) index_min = 0 #绝对值最小的元素的下标 if math.fabs(num_list[index_min]) > math.fabs(num_list[1]): index_min = 1 if math.fabs(num_list[index_min]) > math.fabs(num_list[2]): index_min = 2 for n in num_list: if math.fabs(num_list[index_min]) == math.fabs(n): print(n, end=' ') ''' 5. 从键盘输入非0整数,以输入0为输入结束标志,求平均值,统计正数负数个数 【输入形式】 每个整数一行。最后一行是0,表示输入结束。 【输出形式】输出三行。 第一行是平均值。第二行是正数个数。第三行是负数个数。 ''' nums = [] n_z = 0 n_f = 0 while True: num = int(input()) if num == 0: print(sum(nums)/len(nums)) for n in nums: if n > 0: n_z += 1 elif n < 0: n_f += 1 print(n_z) print(n_f) exit() else: nums.append(num)
0528习题 16-20
''' 11. 编写程序,判断一个数是不是素数,是则输出“Yes”,不是输出“No”.(while循环) ''' num = int(input()) i = 2 flag = True while i < num: if num % i ==0: flag = False i += 1 if flag: print("Yes") else: print("No")
''' 12. 编程实现:从键盘输入5个分数,计算平均分。 【输入形式】5个分数,每个分数占一行。 【输出形式】新起一行输出平均分。 ''' nums = [] for i in range(5): num = float(input()) nums.append(num) print(sum(nums)/len(nums))
''' 13. 输入3个整数,输出其中最大的一个 。 ''' nums = [] for i in range(3): num = int(input()) nums.append(num) print(max(nums))
''' 14. 输入n,计算n!(n!=1*2*3*...*n) ''' n = int(input()) sum = 1 for i in range(1,n+1): sum *= i print(sum)
''' 编写程序,打印菱形图案,行数n从键盘输入。 下为n=3时的图案,其中的点号实际为空格。图案左对齐输出。 ''' n = 3 for i in range(1, n + 1): print(" " * (n - i) + "* " * (2 * i - 1)) for i in range(n-1,0,-1): print(" " * (n - i) + "* " * (2 * i - 1))
0528习题 21-25
''' 16. 编写程序计算学生的平均分。 【输入形式】输入的第一行表示学生人数n; 标准输入的第2至n+1行表示学生成绩。 【输出形式】输出的一行表示平均分(保留两位小数)。 若输入的数据不合法(学生人数不是大于0的整数, 或学生成绩小于0或大于100),输出“illegal input”。 ''' n = int(input()) nums = [] for i in range(n): score = float(input()) if not 0<= score <= 100: print("illegal input") nums.append(score) print("%.2f"%(sum(nums)/len(nums))) ''' 17. 请将一万以内的完全平方数输出 . ''' for x in range(1,101): y = x*x if y <= 10000: print(y) else: break ''' 18. 从键盘输入非0整数,以输入0为输入结束标志,求平均值,统计正数负数个数 【输入形式】每个整数一行。最后一行是0,表示输入结束。 【输出形式】输出三行。 第一行是平均值。第二行是正数个数。第三行是负数个数。 ''' nums = [] n_z = 0 n_f = 0 while True: num = int(input()) if num == 0: print(sum(nums)/len(nums)) for n in nums: if n > 0: n_z += 1 elif n < 0: n_f += 1 print(n_z) print(n_f) exit() else: nums.append(num) ''' 【问题描述】从键盘输入一个大写字母,要求输出其对应的小写字母。 【输入形式】输入大写字母,不考虑不合法输入。 【输出形式】输出对应的小写字母。 【样例输入】A 【样例输出】a ''' s = input() print(s.lower()) ''' 【问题描述】 从键盘输入三个字符,按ASCII码值从小到大排序输出,字符之间间隔一个空格。 【输入形式】 输入三个字符,每个字符用空格隔开。 【输出形式】 相对应的输出按照ASCII码值从小到大排列的三个字符,每个字符间用空格隔开。 【样例输入】a c b 【样例输出】a b c ''' strings = input().split(' ') strings = sorted(strings) for s in strings: print(s,end = " ")
0528习题 26-31
''' 【问题描述】定义一个函数判断是否为素数isPrime(), 主程序通过调用函数输出2-30之间所有的素数。 素数:一个大于1的自然数,除了1和它本身外,不能被其他自然数整除。 【输入形式】无【输出形式】2~30之间所有的索数(逗号分隔) 【样例输入】【样例输出】2,3,5,7,11,13,17,19,23,29, 【样例说明】【评分标准】 ''' def isPrime(n): i = 2 flag = True while i < n: if n % i == 0: flag = False i += 1 if flag: return True else: return False for i in range(2,31): if isPrime(i): print(i,end = ',')
''' 【问题描述】有182只兔子,分别装在甲乙两种笼子里, 甲种笼子(x)每个装6只,乙种笼子(y)每个装4只, 两种笼子正好用36个,问两种笼子各用多少个? 【输入形式】无 【输出形式】笼子的个数 【样例输入】 【样例输出】x=*;y=* 【输出说明】 1)*代表输出的值; 2)输出的等号和分号都是英文字符 ''' for i in range(1,36): x = i y = 36 - i if 6*x + 4*y == 182: print("x=%d;y=%d"%(x,y))
''' 输入圆柱体的底面半径和高,求圆柱体的体积并输出。 圆周率T取固定值3.14。 【输入形式】圆柱体的底面半径和高 【输出形式】圆柱体的体积 【样例输入】2 【样例输出】50.24 ''' r = float(input()) h = float(input()) pi = 3.14 print("%.2f"%(pi*r*r*h))
''' 【问题描述】猴子吃桃问题: 猴子摘下若干个桃子,第一天吃了桃子的一半多一个, 以后每天吃了前一天剩下的一半多一个, 到第n天吃以前发现只剩下一个桃子, 编写程序实现:据输入的天数计算并输出猴子共摘了几个桃子。 【输入形式】n。 【输出形式】共摘了几个桃子 【样例输入】3 【样例输出】10 【样例输入】1 【样例输出】1 ''' day = int(input()) now = 1 yesterday = 0 while day > 1: yesterday = (now + 1) * 2 now = yesterday day -= 1 print(now)
''' 输入5名学生的成绩,保存到列表, 统计最高分、最低分、平均分和及格率。平均分 和及格率保留两位小数,及格率的输出格式为x%。 【输入形式】5个人的成绩 【输出形式】最高分、最低分、平均分、及格率 【样例输入】 56 67 55 66 70 【样例输出】 70 55 62.80 60.00% ''' score = [] for i in range(5): num = float(input()) score.append(num) n = 0 for i in score: if i > 60: n += 1 print(max(score)) print(min(score)) print(sum(score)/len(score)) print("%.2f%%"%(n*100/len(score)))
''' 【问题描述】 文件“in.txt”中存储了学生的姓名和成绩, 每个人的姓名成绩放在一行,中间用空格隔开, 形式如下:Sunny 70 Susan 88从文件读取数据后, 存入字典,姓名作为字典的键,成绩作为字典的值。 然后输入姓名,查询相应的成绩,查不到,显示"not found"。 【输入形式】姓名 【输出形式】成绩 【样例输入】键盘输入:Susan ''' name = input() flag = False with open('in.txt','r',encoding='utf-8') as fp: for line in fp: line = line.replace('\n','') if line != "": lst = line.split() tup = tuple(lst) # print(tup) if tup[0] == name: flag = True print(tup[-1]) if not flag: print("not found") in.txt文件内容 Sunny 70 Susan 80
读取 csv , xlsx 表格并添加总分列
import pandas as pd import numpy as np data = pd.read_excel('学生成绩表.csv',columns = ['学号','姓名','高数','英语','计算机']) sum_score = [ ] for i in range(len(data)): sum_score.append(sum(data.loc[i,:][data.columns[2:]])) data['总分'] = sum_score print(data['总分']) data.to_csv('学生成绩表1.csv',encoding='gbk')
matplotlib 显示中文问题 import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
十进制转换
# bin2dec # 二进制 to 十进e5a48de588b662616964757a686964616f31333335336437制: int(str,n=10) def bin2dec(string_num): return str(int(string_num, 2)) # hex2dec # 十六进制 to 十进制 def hex2dec(string_num): return str(int(string_num.upper(), 16)) # dec2bin # 十进制 to 二进制: bin() def dec2bin(string_num): num = int(string_num) mid = [] while True: if num == 0: break num,rem = divmod(num, 2) mid.append(base[rem]) return ''.join([str(x) for x in mid[::-1]]) # dec2hex # 十进制 to 八进制: oct() # 十进制 to 十六进制: hex() def dec2hex(string_num): num = int(string_num) mid = [] while True: if num == 0: break num,rem = divmod(num, 16) mid.append(base[rem]) return ''.join([str(x) for x in mid[::-1]])
base = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'), ord('A') + 6)] def dec2bin(string_num): '''十进制转换为 二进制''' num = int(string_num) mid = [] while True: if num == 0: break num, rem = divmod(num, 2) mid.append(base[rem]) return ''.join([str(x) for x in mid[::-1]]) def dec2oct(string_num): '''转换为 八进制''' num = int(string_num) mid = [] while True: if num == 0: break num, rem = divmod(num, 8) mid.append(base[rem]) return ''.join([str(x) for x in mid[::-1]]) def dec2hex(string_num): '''转换为 十六进制''' num = int(string_num) mid = [] while True: if num == 0: break num, rem = divmod(num, 16) mid.append(base[rem]) return ''.join([str(x) for x in mid[::-1]]) num = float(input()) print(dec2bin(num),dec2oct(num),dec2hex(num))
正则表达式巩固
# 导入re模块 import re # 使用match方法进行匹配操作 result = re.match(正则表达式,要匹配的字符串) # 如果上一步匹配到数据的话,可以使用group方法来提取数据 result.group()
re.match用来进行正则匹配检查 若字符串匹配正则表达式,则match方法返回匹配对象(Match Object) 否则返回None
import re result = re.match("itcast","itcast.cn") result.group()
re.match() 能够匹配出以xxx开头的字符串
大写字母表示 非 \w 匹配字母,数字,下划线 \W 表示除了字母 数字 下划线的
import re ret = re.match(".","a") ret.group() ret = re.match(".","b") ret.group() ret = re.match(".","M") ret.group()
import re # 如果hello的首字符小写,那么正则表达式需要小写的h ret = re.match("h","hello Python") ret.group() # 如果hello的首字符大写,那么正则表达式需要大写的H ret = re.match("H","Hello Python") ret.group() # 大小写h都可以的情况 ret = re.match("[hH]","hello Python") ret.group() ret = re.match("[hH]","Hello Python") ret.group() # 匹配0到9第一种写法 ret = re.match("[0123456789]","7Hello Python") ret.group() # 匹配0到9第二种写法 ret = re.match("[0-9]","7Hello Python") ret.group()
import re # 普通的匹配方式 ret = re.match("嫦娥1号","嫦娥1号发射成功") print(ret.group()) ret = re.match("嫦娥2号","嫦娥2号发射成功") print(ret.group()) ret = re.match("嫦娥3号","嫦娥3号发射成功") print(ret.group()) # 使用\d进行匹配 ret = re.match("嫦娥\d号","嫦娥1号发射成功") print(ret.group()) ret = re.match("嫦娥\d号","嫦娥2号发射成功") print(ret.group()) ret = re.match("嫦娥\d号","嫦娥3号发射成功") print(ret.group())
正则表达式里使用"\"作为转义字符 需要匹配文本中的字符"\" 使用反斜杠"\\"
import re ret = re.match("[A-Z][a-z]*","Mm") print(ret.group()) ret = re.match("[A-Z][a-z]*","Aabcdef") print(ret.group())
import re ret = re.match("[a-zA-Z_]+[\w_]*","name1") print(ret.group()) ret = re.match("[a-zA-Z_]+[\w_]*","_name") print(ret.group()) ret = re.match("[a-zA-Z_]+[\w_]*","2_name") print(ret.group())
import re ret = re.match("[1-9]?[0-9]","7") print(ret.group()) ret = re.match("[1-9]?[0-9]","33") print(ret.group()) ret = re.match("[1-9]?[0-9]","09") print(ret.group())
import re ret = re.match("[a-zA-Z0-9_]{6}","12a3g45678") print(ret.group()) ret = re.match("[a-zA-Z0-9_]{8,20}","1ad12f23s34455ff66") print(ret.group())
import re # 正确的地址 ret = re.match("[\w]{4,20}@163\.com", "xiaoWang@163.com") print(ret.group()) # 不正确的地址 ret = re.match("[\w]{4,20}@163\.com", "xiaoWang@163.comheihei") print(ret.group()) # 通过$来确定末尾 ret = re.match("[\w]{4,20}@163\.com$", "xiaoWang@163.comheihei") print(ret.group())
\b 匹配一个单词的边界 \B 匹配非单词边界
import re ret = re.match("[1-9]?\d","8") print(ret.group()) ret = re.match("[1-9]?\d","78") print(ret.group()) # 添加| ret = re.match("[1-9]?\d$|100","8") print(ret.group()) ret = re.match("[1-9]?\d$|100","78") print(ret.group()) ret = re.match("[1-9]?\d$|100","100") print(ret.group())
import re ret = re.match("\w{4,20}@163\.com", "test@163.com") print(ret.group()) ret = re.match("\w{4,20}@(163|126|qq)\.com", "test@126.com") print(ret.group()) ret = re.match("\w{4,20}@(163|126|qq)\.com", "test@qq.com") print(ret.group())
import re # 能够完成对正确的字符串的匹配 ret = re.match("<[a-zA-Z]*>\w*</[a-zA-Z]*>", "<html>hh</html>") print(ret.group()) # 如果遇到非正常的html格式字符串,匹配出错 ret = re.match("<[a-zA-Z]*>\w*</[a-zA-Z]*>", "<html>hh</htmlbalabala>") print(ret.group()) # 正确的理解思路:如果在第一对<>中是什么,按理说在后面的那对<>中就应该是什么 # 通过引用分组中匹配到的数据即可,但是要注意是元字符串,即类似 r""这种格式 ret = re.match(r"<([a-zA-Z]*)>\w*</\1>", "<html>hh</html>") print(ret.group()) # 因为2对<>中的数据不一致,所以没有匹配出来 ret = re.match(r"<([a-zA-Z]*)>\w*</\1>", "<html>hh</htmlbalabala>") print(ret.group())
import re ret = re.match(r"<(\w*)><(\w*)>.*</\2></\1>", "<html><h1>www.itcast.cn</h1></html>") print(ret.group()) # 因为子标签不同,导致出错 ret = re.match(r"<(\w*)><(\w*)>.*</\2></\1>", "<html><h1>www.itcast.cn</h2></html>") print(ret.group())
import re ret = re.match(r"<(?P<name1>\w*)><(?P<name2>\w*)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itcast.cn</h1></html>") print(ret.group()) ret = re.match(r"<(?P<name1>\w*)><(?P<name2>\w*)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itcast.cn</h2></html>") print(ret.group())
import re ret = re.search(r"\d+", "阅读次数为 9999") print(ret.group())
import re ret = re.findall(r"\d+", "python = 9999, c = 7890, c++ = 12345") print(ret)
import re ret = re.sub(r"\d+", '998', "python = 997") print(ret)
import re def add(temp): strNum = temp.group() num = int(strNum) + 1 return str(num) # 替换的是 原数据 + 1 ret = re.sub(r"\d+", add, "python = 997") print(ret) ret = re.sub(r"\d+", add, "python = 99") print(ret)
import re ret = re.split(r":| ","info:xiaoZhang 33 shandong") print(ret)
Python里数量词默认是贪婪的 匹配尽可能多的字符 非贪婪 总匹配尽可能少的字符。
pandas巩固
导包 import pandas as pd
设置输出结果列对齐 pd.set_option('display.unicode.ambiguous_as_wide',True) pd.set_option('display.unicode.east_asian_width',True)
创建 从 0 开始的非负整数索引 s1 = pd.Series(range(1,20,5))
使用字典创建 Series 字典的键作为索引 s2 = pd.Series({'语文':95,'数学':98,'Python':100,'物理':97,'化学':99})
修改 Series 对象的值 s1[3] = -17
查看 s1 的绝对值 abs(s1)
将 s1 所有的值都加 5、使用加法时,对所有元素都进行 s1 + 5
在 s1 的索引下标前加入参数值 s1.add_prefix(2)
s2 数据的直方图 s2.hist()
每行索引后面加上 hany s2.add_suffix('hany')
查看 s2 中最大值的索引 s2.argmax()
查看 s2 的值是否在指定区间内 s2.between(90,100,inclusive = True)
查看 s2 中 97 分以上的数据 s2[s2 > 97]
查看 s2 中大于中值的数据 s2[s2 > s2.median()]
s2 与数字之间的运算,开平方根 * 10 保留一位小数 round((s2**0.5)*10,1)
s2 的中值 s2.median()
s2 中最小的两个数 s2.nsmallest(2)
s2 中最大的两个数 s2.nlargest(2)
Series 对象之间的运算,对相同索引进行计算,不是相同索引的使用 NaN pd.Series(range(5)) + pd.Series(range(5,10))
对 Series 对象使用匿名函数 pd.Series(range(5)).pipe(lambda x,y,z :(x**y)%z,2,5)
pd.Series(range(5)).pipe(lambda x:x+3)
pd.Series(range(5)).pipe(lambda x:x+3).pipe(lambda x:x*3)
对 Series 对象使用匿名函数 pd.Series(range(5)).apply(lambda x:x+3)
查看标准差 pd.Series(range(0,5)).std()
查看无偏方差 pd.Series(range(0,5)).var()
查看无偏标准差 pd.Series(range(0,5)).sem()
查看是否存在等价于 True 的值 any(pd.Series([3,0,True]))
查看是否所有的值都等价于 True all(pd.Series([3,0,True]))
创建一个 DataFrame 对象 dataframe = pd.DataFrame(np.random.randint(1,20,(5,3)), index = range(5), columns = ['A','B','C'])
索引为时间序列 dataframe2 = pd.DataFrame(np.random.randint(5,15,(9,3)), index = pd.date_range(start = '202003211126', end = '202003212000', freq = 'H'), columns = ['Pandas','爬虫','比赛'])
使用字典进行创建 dataframe3 = pd.DataFrame({'语文':[87,79,67,92], '数学':[93,89,80,77], '英语':[88,95,76,77]}, index = ['张三','李四','王五','赵六'])
创建时自动扩充 dataframe4 = pd.DataFrame({'A':range(5,10),'B':3})
查看周几 dff['日期'] = pd.to_datetime(data['日期']).dt.weekday_name
按照周几进行分组,查看交易的平均值 dff = dff.groupby('日期').mean().apply(round) dff.index.name = '周几'
对姓名和日期进行分组,并进行求和 dff = dataframe.groupby(by = ['姓名','日期'],as_index = False).sum()
将 dff 的索引,列 设置成透视表形式 dff = dff.pivot(index = '姓名',columns = '日期',values = '交易额')
查看前一天的数据 dff.iloc[:,:1]
交易总额小于 4000 的人的前三天业绩 dff[dff.sum(axis = 1) < 4000].iloc[:,:3]
工资总额大于 2900 元的员工的姓名 dff[dff.sum(axis = 1) > 2900].index.values
显示前两天每一天的交易总额以及每个人的交易金额 dataframe.pivot_table(values = '交易额',index = '姓名', columns = '日期',aggfunc = 'sum',margins = True).iloc[:,:2]
显示每个人在每个柜台的交易总额 dff = dataframe.groupby(by = ['姓名','柜台'],as_index = False).sum()
dff.pivot(index = '姓名',columns = '柜台',values = '交易额')
查看每人每天的上班次数 dataframe.pivot_table(values = '交易额',index = '姓名',columns = '日期',aggfunc = 'count',margins = True).iloc[:,:1]
查看每个人每天购买的次数 dataframe.pivot_table(values = '交易额',index = '姓名',columns = '日期',aggfunc = 'count',margins = True)
每个人每天上过几次班 pd.crosstab(dataframe.姓名,dataframe.日期,margins = True).iloc[:,:2]
每个人每天去过几次柜台 pd.crosstab(dataframe.姓名,dataframe.柜台)
将每一个人在每一个柜台的交易总额显示出来 pd.crosstab(dataframe.姓名,dataframe.柜台,dataframe.交易额,aggfunc='sum')
每个人在每个柜台交易额的平均值,金额/天数 pd.crosstab(dataframe.姓名,dataframe.柜台,dataframe.交易额,aggfunc = 'mean').apply(lambda num:round(num,2) )
对 5 的余数进行分组 dataframe.groupby(by = lambda num:num % 5)['交易额'].sum()
查看索引为 7 15 的交易额 dataframe.groupby(by = {7:'索引为7的行',15:'索引为15的行'})['交易额'].sum()
查看不同时段的交易总额 dataframe.groupby(by = '时段')['交易额'].sum()
各柜台的销售总额 dataframe.groupby(by = '柜台')['交易额'].sum()
查看每个人在每个时段购买的次数 count = dataframe.groupby(by = '姓名')['时段'].count()
每个人的交易额平均值并排序 dataframe.groupby(by = '姓名')['交易额'].mean().round(2).sort_values()
每个人的交易额,apply(int) 转换为整数 dataframe.groupby(by = '姓名').sum()['交易额'].apply(int)
每一个员工交易额的中值 data = dataframe.groupby(by = '姓名').median()
查看交易额对应的排名 data['排名'] = data['交易额'].rank(ascending = False)
data[['交易额','排名']]
每个人不同时段的交易额 dataframe.groupby(by = ['姓名','时段'])['交易额'].sum()
设置各时段累计 dataframe.groupby(by = ['姓名'])['时段','交易额'].aggregate({'交易额':np.sum,'时段':lambda x:'各时段累计'})
对指定列进行聚合,查看最大,最小,和,平均值,中值 dataframe.groupby(by = '姓名').agg(['max','min','sum','mean','median'])
查看部分聚合后的结果 dataframe.groupby(by = '姓名').agg(['max','min','sum','mean','median'])['交易额']
查看交易额低于 2000 的三条数据 dataframe[dataframe.交易额 < 2000][:3]
查看上浮了 50% 之后依旧低于 1500 的交易额,查看 4 条数据 dataframe.loc[dataframe.交易额 < 1500,'交易额'] = dataframe[dataframe.交易额 < 1500]['交易额'].map(lambda num:num*1.5)
查看交易额大于 2500 的数据 dataframe[dataframe.交易额 > 2500]
查看交易额低于 900 或 高于 1800 的数据 dataframe[(dataframe.交易额 < 900)|(dataframe.交易额 > 1800)]
将所有低于 200 的交易额都替换成 200 dataframe.loc[dataframe.交易额 < 200,'交易额'] = 200
查看低于 1500 的交易额个数 dataframe.loc[dataframe.交易额 < 1500,'交易额'].count()
将大于 3000 元的都替换为 3000 元 dataframe.loc[dataframe.交易额 > 3000,'交易额'] = 3000
查看有多少行数据 len(dataframe)
丢弃缺失值之后的行数 len(dataframe.dropna())
包含缺失值的行 dataframe[dataframe['交易额'].isnull()]
使用固定值替换缺失值 dff = copy.deepcopy(dataframe) dff.loc[dff.交易额.isnull(),'交易额'] = 999
使用交易额的均值替换缺失值 dff = copy.deepcopy(dataframe) for i in dff[dff.交易额.isnull()].index: dff.loc[i,'交易额'] = round(dff.loc[dff.姓名 == dff.loc[i,'姓名'],'交易额'].mean())
使用整体均值的 80% 填充缺失值 dataframe.fillna({'交易额':round(dataframe['交易额'].mean() * 0.8)},inplace = True)
查看重复值 dataframe[dataframe.duplicated()]
丢弃重复行 dataframe = dataframe.drop_duplicates()
查看员工业绩波动情况(每一天和昨天的数据作比较) dff = dataframe.groupby(by = '日期').sum()['交易额'].diff()
对数据使用 map 函数 dff.map(lambda num:'%.2f'%(num))[:5]
查看张三的波动情况 dataframe[dataframe.姓名 == '张三'].groupby(by = '日期').sum()['交易额'].diff()
修改异常值 data.loc[data.交易额 > 3000,'交易额'] = 3000 data.loc[data.交易额 < 200,'交易额'] = 200
删除重复值 data.drop_duplicates(inplace = True)
填充缺失值 data['交易额'].fillna(data['交易额'].mean(),inplace = True)
使用交叉表得到每人在各柜台交易额的平均值 data_group = pd.crosstab(data.姓名,data.柜台,data.交易额,aggfunc = 'mean').apply(round)
绘制柱状图 data_group.plot(kind = 'bar')
使用 concat 连接两个相同结构的 DataFrame 对象 df3 = pd.concat([df1,df2])
合并,忽略原来的索引 ignore_index df4 = df3.append([df1,df2],ignore_index = True)
按照列进行拆分 df5 = df4.loc[:,['姓名','柜台','交易额']]
按照工号进行合并,随机查看 3 条数据 rows = np.random.randint(0,len(df5),3) pd.merge(df4,df5).iloc[rows,:]
按照工号进行合并,指定其他同名列的后缀 pd.merge(df1,df2,on = '工号',suffixes = ['_x','_y']).iloc[:,:]
两个表都设置工号为索引 set_index df2.set_index('工号').join(df3.set_index('工号'),lsuffix = '_x',rsuffix = '_y').iloc[:]
按照交易额和工号降序排序,查看五条数据 dataframe.sort_values(by = ['交易额','工号'],ascending = False)[:5]
按照交易额和工号升序排序,查看五条数据 dataframe.sort_values(by = ['交易额','工号'])[:5]
按照交易额降序和工号升序排序,查看五条数据 dataframe.sort_values(by = ['交易额','工号'],ascending = [False,True])[:5]
按工号升序排序 dataframe.sort_values(by = ['工号'])[:5]
按列名升序排序 dataframe.sort_index(axis = 1)[:5]
每隔五天--5D pd.date_range(start = '20200101',end = '20200131',freq = '5D')
每隔一周--W pd.date_range(start = '20200301',end = '20200331',freq = 'W')
间隔两天,五个数据 pd.date_range(start = '20200301',periods = 5,freq = '2D')
间隔三小时,八个数据 pd.date_range(start = '20200301',periods = 8,freq = '3H')
三点开始,十二个数据,间隔一分钟 pd.date_range(start = '202003010300',periods = 12,freq = 'T')
每个月的最后一天 pd.date_range(start = '20190101',end = '20191231',freq = 'M')
间隔一年,六个数据,年末最后一天 pd.date_range(start = '20190101',periods = 6,freq = 'A')
间隔一年,六个数据,年初最后一天 pd.date_range(start = '20200101',periods = 6,freq = 'AS')
使用 Series 对象包含时间序列对象,使用特定索引 data = pd.Series(index = pd.date_range(start = '20200321',periods = 24,freq = 'H'),data = range(24))
三分钟重采样,计算均值 data.resample('3H').mean()
五分钟重采样,求和 data.resample('5H').sum()
计算OHLC open,high,low,close data.resample('5H').ohlc()
将日期替换为第二天 data.index = data.index + pd.Timedelta('1D')
查看指定日期的年份是否是闰年 pd.Timestamp('20200301').is_leap_year
查看指定日期所在的季度和月份 day = pd.Timestamp('20200321')
查看日期的季度 day.quarter
查看日期所在的月份 day.month
转换为 python 的日期时间对象 day.to_pydatetime()
查看所有的交易额信息 dataframe['交易额'].describe()
查看四分位数 dataframe['交易额'].quantile([0,0.25,0.5,0.75,1.0])
查看最大的交易额数据 dataframe.nlargest(2,'交易额')
查看最后一个日期 dataframe['日期'].max()
查看最小的工号 dataframe['工号'].min()
第一个最小交易额的行下标 index = dataframe['交易额'].idxmin()
第一个最小交易额 dataframe.loc[index,'交易额']
最大交易额的行下标 index = dataframe['交易额'].idxmax()
跳过 1 2 4 行,以第一列姓名为索引 dataframe2 = pd.read_excel('超市营业额.xlsx', skiprows = [1,2,4], index_col = 1)
查看 5 到 10 的数据 dataframe[5:11]
查看第六行的数据 dataframe.iloc[5]
查看第 1 3 4 行的数据 dataframe.iloc[[0,2,3],:]
查看第 1 3 4 行的第 1 2 列 dataframe.iloc[[0,2,3],[0,1]]
查看前五行指定,姓名、时段和交易额的数据 dataframe[['姓名','时段','交易额']][:5]
查看第 2 4 5 行 姓名,交易额 数据 loc 函数 dataframe.loc[[1,3,4],['姓名','交易额']]
查看第四行的姓名数据 dataframe.at[3,'姓名']
某一时段的交易总和 dataframe[dataframe['时段'] == '14:00-21:00']['交易额'].sum()
查看张三总共的交易额 dataframe[dataframe['姓名'].isin(['张三'])]['交易额'].sum()
查看日用品的销售总额 dataframe[dataframe['柜台'] == '日用品']['交易额'].sum()
查看交易额在 1500~3000 之间的记录 dataframe[dataframe['交易额'].between(1500,3000)]
将日期设置为 python 中的日期类型 data.日期 = pd.to_datetime(data.日期)
每七天营业的总额 data.resample('7D',on = '日期').sum()['交易额']
每七天营业总额 data.resample('7D',on = '日期',label = 'right').sum()['交易额']
每七天营业额的平均值 func = lambda item:round(np.sum(item)/len(item),2) data.resample('7D',on = '日期',label = 'right').apply(func)['交易额']
每七天营业额的平均值 func = lambda num:round(num,2) data.resample('7D',on = '日期',label = 'right').mean().apply(func)['交易额']
删除工号这一列 data.drop('工号',axis = 1,inplace = True)
按照姓名和柜台进行分组汇总 data = data.groupby(by = ['姓名','柜台']).sum()
查看张三的汇总数据 data.loc['张三',:]
查看张三在蔬菜水果的交易数据 data.loc['张三','蔬菜水果']
丢弃工号列 data.drop('工号',axis = 1,inplace = True)
按照柜台进行排序 dff = data.sort_index(level = '柜台',axis = 0)
按照姓名进行排序 dff = data.sort_index(level = '姓名',axis = 0)
按照柜台进行分组求和 dff = data.groupby(level = '柜台').sum()['交易额']
平均值 data.mean()
标准差 data.std()
协方差 data.cov()
删除缺失值和重复值,inplace = True 直接丢弃 data.dropna(inplace = True) data.drop_duplicates(inplace = True)
numpy巩固
导包 import numpy as np
创建二维数组 x = np.matrix([[1,2,3],[4,5,6]])
创建一维数组 y = np.matrix([1,2,3,4,5,6])
x 的第二行第二列元素 x[1,1]
矩阵的乘法 x*y
# 相关系数矩阵,可使用在列表元素数组矩阵 # 负相关 np.corrcoef([1,2,3],[8,5,4]) ''' array([[ 1. , -0.96076892], [-0.96076892, 1. ]]) ''' # 正相关 np.corrcoef([1,2,3],[4,5,7]) ''' array([[1. , 0.98198051], [0.98198051, 1. ]]) '''
矩阵的方差 np.cov([1,1,1,1,1])
矩阵的标准差 np.std([1,1,1,1,1])
垂直堆叠矩阵 z = np.vstack((x,y))
矩阵的协方差 np.cov(z)
np.cov(x,y)
标准差 np.std(z)
列向标准差 np.std(z,axis = 1)
方差 np.cov(x)
特征值和特征向量 A = np.array([[1,-3,3],[3,-5,3],[6,-6,4]]) e,v = np.linalg.eig(A) e 为特征值, v 为特征向量
矩阵与特征向量的乘积 np.dot(A,v)
特征值与特征向量的乘积 e * v
验证两个乘积是否相等 np.isclose(np.dot(A,v),(e * v))
行列式 |A - λE| 的值应为 0 np.linalg.det(A-np.eye(3,3)*e)
逆矩阵 y = np.linalg.inv(x)
矩阵的乘法(注意先后顺序) x * y ''' matrix([[ 1.00000000e+00, 5.55111512e-17, 1.38777878e-17], [ 5.55111512e-17, 1.00000000e+00, 2.77555756e-17], [ 1.77635684e-15, -8.88178420e-16, 1.00000000e+00]]) ''' y * x ''' matrix([[ 1.00000000e+00, -1.11022302e-16, 0.00000000e+00], [ 8.32667268e-17, 1.00000000e+00, 2.22044605e-16], [ 6.93889390e-17, 0.00000000e+00, 1.00000000e+00]]) '''
求解线性方程组 a = np.array([[3,1],[1,2]]) b = np.array([9,8]) x = np.linalg.solve(a,b)
最小二乘解:返回解,余项,a 的秩,a 的奇异值 np.linalg.lstsq(a,b) # (array([2., 3.]), array([], dtype=float64), 2, array([3.61803399, 1.38196601]))
计算向量和矩阵的范数 x = np.matrix([[1,2],[3,-4]]) np.linalg.norm(x) # 5.477225575051661 np.linalg.norm(x,-2) # 1.9543950758485487 np.linalg.norm(x,-1) # 4.0 np.linalg.norm(x,1) # 6.0 np.linalg.norm([1,2,0,3,4,0],0) # 4.0 np.linalg.norm([1,2,0,3,4,0],2) # 5.477225575051661
奇异值分解 a = np.matrix([[1,2,3],[4,5,6],[7,8,9]]) u,s,v = np.linalg.svd(a) u ''' matrix([[-0.21483724, 0.88723069, 0.40824829], [-0.52058739, 0.24964395, -0.81649658], [-0.82633754, -0.38794278, 0.40824829]]) ''' s ''' array([1.68481034e+01, 1.06836951e+00, 4.41842475e-16]) ''' v ''' matrix([[-0.47967118, -0.57236779, -0.66506441], [-0.77669099, -0.07568647, 0.62531805], [-0.40824829, 0.81649658, -0.40824829]]) ''' # 验证 u * np.diag(s) * v ''' matrix([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) '''
实现矩阵的转置 x.T
元素平均值 x.mean()
纵向平均值 x.mean(axis = 0)
横向平均值 x.mean(axis = 1)
所有元素之和 x.sum()
横向最大值 x.max(axis = 1)
横向最大值的索引下标 x.argmax(axis = 1)
对角线元素 x.diagonal()
非零元素下标 x.nonzero()
创建数组 np.array([1,2,3,4])
np.array((1,2,3,4))
np.array(range(4)) # 不包含终止数字 # array([0, 1, 2, 3])
# 使用 arange(初始位置=0,末尾,步长=1) np.arange(1,8,2) # array([1, 3, 5, 7])
生成等差数组,endpoint 为 True 则包含末尾数字 np.linspace(1,3,4,endpoint=False) # array([1. , 1.5, 2. , 2.5]) np.linspace(1,3,4,endpoint=True) # array([1. , 1.66666667, 2.33333333, 3. ])
创建全为零的一维数组 np.zeros(3)
创建全为一的一维数组 np.ones(4)
np.linspace(1,3,4) # array([1. , 1.66666667, 2.33333333, 3. ])
np.logspace(起始数字,终止数字,数字个数,base = 10) 对数数组 np.logspace(1,3,4) # 相当于 10 的 linspace(1,3,4) 次方 # array([ 10. , 46.41588834, 215.443469 , 1000. ]) np.logspace(1,3,4,base = 2) # 2 的 linspace(1,3,4) 次方 # array([2. , 3.1748021, 5.0396842, 8. ])
创建二维数组(列表嵌套列表) np.array([[1,2,3],[4,5,6]])
# 创建全为零的二维数组 # 两行两列 np.zeros((2,2))
三行两列 np.zeros((3,2))
# 创建一个单位数组 np.identity(3) ''' array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) '''
创建一个对角矩阵,(参数为对角线上的数字) np.diag((1,2,3)) ''' array([[1, 0, 0], [0, 2, 0], [0, 0, 3]]) '''
第一行元素 n[0]
第一行第三列元素 n[0,2]
第一行和第二行的元素 n[[0,1]]
第一行第三列,第三行第二列,第二行第一列 n[[0,2,1],[2,1,0]]
将数组倒序 a[::-1]
步长为 2 a[::2]
从 0 到 4 的元素 a[:5]
变换 c 的矩阵行和列 c = np.arange(16) # array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) c.shape = 4,4 ''' array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) '''
第一行,第三个元素到第五个元素(如果没有则输出到末尾截止) c[0,2:5]
第二行元素 c[1]
第三行到第六行,第三列到第六列 c[2:5,2:5]
第二行第三列元素和第三行第四列元素 c[[1,2],[2,3]]
第一行和第三行的第二列到第三列的元素 c[[0,2],1:3]
第一列和第三列的所有横行元素 c[:,[0,2]]
第三列所有元素 c[:,2]
第二行和第四行的所有元素 c[[1,3]]
第一行的第二列,第四列元素,第四行的第二列,第四列元素 c[[0,3]][:,[1,3]]
使用 * 进行相乘 x*2
使用 / 进行相除 x / 2
2 / x
使用 // 进行整除 x//2
10//x
使用 ** 进行幂运算 x**3
2 ** x
使用 + 进行相加 x + 2
使用 % 进行取模 x % 3
使用 + 进行相加 np.array([1,2,3,4]) + np.array([11,22,33,44]) np.array([1,2,3,4]) + np.array([3]) # array([4, 5, 6, 7])
数组的内积运算(对应位置上元素相乘) np.dot(x,y)
sum(x*y)
将数组中大于 0.5 的元素显示 n[n>0.5]
找到数组中 0.05 ~ 0.4 的元素总数 sum((n > 0.05)&(n < 0.4))
是否都大于 0.2 np.all(n > 0.2)
是否有元素小于 0.1 np.any(n < 0.1)
在 a 中是否有大于 b 的元素 a > b # array([False, True, False]) # 在 a 中是否有等于 b 的元素 a == b # array([False, False, True]) # 显示 a 中 a 的元素等于 b 的元素 a[a == b] # array([7])
显示 a 中的偶数且小于 5 的元素 a[(a%2 == 0) & (a < 5)]
生成一个随机数组 np.random.randint(0,6,3)
生成一个随机数组(二维数组) np.random.randint(0,6,(3,3))
生成十个随机数在[0,1)之间 np.random.rand(10) ''' array([0.9283789 , 0.43515554, 0.27117021, 0.94829333, 0.31733981, 0.42314939, 0.81838647, 0.39091899, 0.33571004, 0.90240897]) '''
从标准正态分布中随机抽选出3个数 np.random.standard_normal(3)
返回三页四行两列的标准正态分布数 np.random.standard_normal((3,4,2))
x = np.arange(8) 在数组尾部追加一个元素 np.append(x,10) 在数组尾部追加多个元素 np.append(x,[15,16,17])
使用 数组下标修改元素的值 x[0] = 99
在指定位置插入数据 np.insert(x,0,54)
创建一个多维数组 x = np.array([[1,2,3],[11,22,33],[111,222,333]]) 修改第 0 行第 2 列的元素值 x[0,2] = 9
行数大于等于 1 的,列数大于等于 1 的置为 1 x[1:,1:] = 1
# 同时修改多个元素值 x[1:,1:] = [7,8] ''' array([[ 1, 2, 9], [ 11, 7, 8], [111, 7, 8]]) ''' x[1:,1:] = [[7,8],[9,10]] ''' array([[ 1, 2, 9], [ 11, 7, 8], [111, 9, 10]]) '''
查看数组的大小 n.size
将数组分为两行五列 n.shape = 2,5
显示数组的维度 n.shape
设置数组的维度,-1 表示自动计算 n.shape = 5,-1
将新数组设置为调用数组的两行五列并返回 x = n.reshape(2,5)
x = np.arange(5) # 将数组设置为两行,没有数的设置为 0 x.resize((2,10)) ''' array([[0, 1, 2, 3, 4, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) ''' # 将 x 数组的两行五列形式显示,不改变 x 的值 np.resize(x,(2,5)) ''' array([[0, 1, 2, 3, 4], [0, 0, 0, 0, 0]]) '''
x = np.array([1,4,5,2]) # array([1, 4, 5, 2]) # 返回排序后元素的原下标 np.argsort(x) # array([0, 3, 1, 2], dtype=int64)
输出最大值的下标 x.argmax( )
输出最小值的下标 x.argmin( )
对数组进行排序 x.sort( )
每个数组元素对应的正弦值 np.sin(x)
每个数组元素对应的余弦值 np.cos(x)
对参数进行四舍五入 np.round(np.cos(x))
对参数进行上入整数 3.3->4 np.ceil(x/3)
# 分段函数 x = np.random.randint(0,10,size=(1,10)) # array([[0, 3, 6, 7, 9, 4, 9, 8, 1, 8]]) # 大于 4 的置为 0 np.where(x > 4,0,1) # array([[1, 1, 0, 0, 0, 1, 0, 0, 1, 0]]) # 小于 4 的乘 2 ,大于 7 的乘3 np.piecewise(x,[x<4,x>7],[lambda x:x*2,lambda x:x*3]) # array([[ 0, 6, 0, 0, 27, 0, 27, 24, 2, 24]])
数据库 mysql-connector 基础
安装驱动 python -m pip install mysql-connector
导包 import mysql.connector
mydb = mysql.connector.connect( host="localhost", # 数据库主机地址 user="root", # 数据库用户名 passwd="root" # 数据库密码 )
创建游标 mycursor = mydb.cursor()
使用 mycursor.execute("sql 语句") 进行运行 mycursor.execute("CREATE DATABASE runoob_db")
指定数据库名为 runoob_db mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="runoob_db" )
创建数据表 mycursor.execute("CREATE TABLE sites (name VARCHAR(255), url VARCHAR(255))")
查看当前数据表有哪些 mycursor.execute("SHOW TABLES")
使用 "INT AUTO_INCREMENT PRIMARY KEY" 语句 创建一个主键,主键起始值为 1,逐步递增 mycursor.execute("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
创建表时,添加主键 mycursor.execute("CREATE TABLE sites (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), url VARCHAR(255))")
插入数据 sql = "INSERT INTO sites (name, url) VALUES (%s, %s)" val = ("RUNOOB", "https://www.runoob.com") mycursor.execute(sql, val) mydb.commit() # 数据表内容有更新,必须使用到该语句
打印 行号 mycursor.rowcount
插入多条语句 sql = "INSERT INTO sites (name, url) VALUES (%s, %s)" val = [ ('Google', 'https://www.google.com'), ('Github', 'https://www.github.com'), ('Taobao', 'https://www.taobao.com'), ('stackoverflow', 'https://www.stackoverflow.com/') ] mycursor.executemany(sql, val) mydb.commit() # 数据表内容有更新,必须使用到该语句
在数据插入后,获取该条记录的 ID mycursor.lastrowid
使用 fetchall() 获取所有记录 mycursor.execute("SELECT * FROM sites") myresult = mycursor.fetchall() for x in myresult: print(x)
选取指定数据进行查找 mycursor.execute("SELECT name, url FROM sites") myresult = mycursor.fetchall() for x in myresult: print(x)
使用 .fetchone() 获取一条数据 mycursor.execute("SELECT * FROM sites") myresult = mycursor.fetchone() print(myresult)
使用 where 语句 sql = "SELECT * FROM sites WHERE name ='RUNOOB'" mycursor.execute(sql) myresult = mycursor.fetchall()
使用 fetchall 之后,需要使用循环进行输出 for x in myresult: print(x)
使用 通配符 % sql = "SELECT * FROM sites WHERE url LIKE '%oo%'"
使用 %s 防止发生 SQL 注入攻击 sql = "SELECT * FROM sites WHERE name = %s" na = ("RUNOOB", ) mycursor.execute(sql, na)
排序 使用 ORDER BY 语句,默认升序,关键字为 ASC 如果要设置降序排序,可以设置关键字 DESC
sql = "SELECT * FROM sites ORDER BY name" mycursor.execute(sql)
降序 DESC sql = "SELECT * FROM sites ORDER BY name DESC" mycursor.execute(sql)
使用 limit 设置查询的数据量 mycursor.execute("SELECT * FROM sites LIMIT 3")
limit 指定起始位置 使用 offset mycursor.execute("SELECT * FROM sites LIMIT 3 OFFSET 1") # 0 为 第一条,1 为第二条,以此类推 myresult = mycursor.fetchall()
删除记录 delete from sql = "DELETE FROM sites WHERE name = 'stackoverflow'" mycursor.execute(sql)
sql = "DELETE FROM sites WHERE name = %s" na = ("stackoverflow", ) mycursor.execute(sql, na)
更新表中数据 update sql = "UPDATE sites SET name = 'ZH' WHERE name = 'Zhihu'" mycursor.execute(sql)
sql = "UPDATE sites SET name = %s WHERE name = %s" val = ("Zhihu", "ZH") mycursor.execute(sql, val)
删除表 drop table 可以先使用 if exists 判断是否存在 sql = "DROP TABLE IF EXISTS sites" # 删除数据表 sites mycursor.execute(sql)
爬虫流程(前面发过的文章的合集)巩固
1.打开网页 urllib.request.urlopen('网址')
例:response = urllib.request.urlopen('http://www.baidu.com/') 返回值为 <http.client.HTTPResponse object at 0x00000224EC2C9490>
2.获取响应头信息 urlopen 对象.getheaders() 例:response.getheaders() 返回值为 [('Bdpagetype', '1'), ('Bdqid', '0x8fa65bba0000ba44'),···,('Transfer-Encoding', 'chunked')] [('头','信息')]
3.获取响应头信息,带参数表示指定响应头 urlopen 对象.getheader('头信息') 例:response.getheader('Content-Type') 返回值为 'text/html;charset=utf-8'
4.查看状态码 urlopen 对象.status 例:response.status 返回值为 200 则表示成功
5.得到二进制数据,然后转换为 utf-8 格式 二进制数据 例:html = response.read() HTML 数据格式 例:html = response.read().decode('utf-8') 打印输出时,使用 decode('字符集') 的数据 print(html.decode('utf-8'))
6.存储 HTML 数据 fp = open('文件名.html','模式 wb') 例:fp = open('baidu.html', 'wb') fp.write(response.read() 对象) 例:fp.write(html)
7.关闭文件 open对象.close() 例:fp.close()
8.使用 ssl 进行抓取 https 的网页 例: import ssl content = ssl._create_unverified_context() headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'} request = urllib.request.Request('http://www.baidu.com/', headers = headers) response = urllib.request.urlopen(request, context = context) 这里的 response 就和上面一样了
9.获取码 response.getcode() 返回值为 200
10.获取爬取的网页 url response.geturl() 返回值为 https://www.baidu.com/
11.获取响应的报头信息 response.info()
12.保存网页 urllib.request.urlretrieve(url, '文件名.html') 例:urllib.request.urlretrieve(url, 'baidu.html')
13.保存图片 urllib.request.urlretrieve(url, '图片名.jpg') 例:urllib.request.urlretrieve(url, 'Dog.jpg')
其他字符(如汉字)不符合标准时,要进行编码 14.除了-._/09AZaz 都会编码 urllib.parse.quote() 例: Param = "全文检索:*" urllib.parse.quote(Param) 返回值为 '%E5%85%A8%E6%96%87%E6%A3%80%E7%B4%A2%3A%2A'
15.会编码 / 斜线(将斜线也转换为 %.. 这种格式) urllib.parse.quote_plus(Param)
16.将字典拼接为 query 字符串 如果有中文,进行url编码 dic_object = { 'user_name':'张三', 'user_passwd':'123456' } urllib.parse.urlencode(dic_object) 返回值为 'user_name=%E5%BC%A0%E4%B8%89&user_passwd=123456'
17.获取 response 的行 url = 'http://www.baidu.com' response = urllib.request.urlopen(url) response.readline()
18.随机获取请求头(随机包含请求头信息的列表) user_agent = [ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv2.0.1) Gecko/20100101 Firefox/4.0.1", "Mozilla/5.0 (Windows NT 6.1; rv2.0.1) Gecko/20100101 Firefox/4.0.1", "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11", "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11" ] ua = random.choice(user_agent) headers = {'User-Agent':ua}
19.对输入的汉字进行 urlencode 编码 urllib.parse.urlencode(字典对象) 例: chinese = input('请输入要查询的中文词语:') wd = {'wd':chinese} wd = urllib.parse.urlencode(wd) 返回值为 'wd=%E4%BD%A0%E5%A5%BD'
20.常见分页操作 for page in range(start_page, end_page + 1): pn = (page - 1) * 50
21.通常会进行拼接字符串形成网址 例:fullurl = url + '&pn=' + str(pn)
22.进行拼接形成要保存的文件名 例:filename = 'tieba/' + name + '贴吧_第' + str(page) + '页.html'
23.保存文件 with open(filename,'wb') as f: f.write(reponse.read() 对象)
24.headers 头信息可以删除的有 cookie、accept-encoding、accept-languag、content-length\connection\origin\host
25.headers 头信息不可以删除的有 Accept、X-Requested-With、User-Agent、Content-Type、Referer
26.提交给网页的数据 formdata formdata = { 'from':'en', 'to':'zh', 'query':word, 'transtype':'enter', 'simple_means_flag':'3' }
27.将formdata进行urlencode编码,并且转化为bytes类型 formdata = urllib.parse.urlencode(formdata).encode('utf-8')
28.使用 formdata 在 urlopen() 中 response = urllib.request.urlopen(request, data=formdata)
29.转换为正确数据(导包 json) read -> decode -> loads -> json.dumps 通过read读取过来为字节码 data = response.read() 将字节码解码为utf8的字符串 data = data.decode('utf-8') 将json格式的字符串转化为json对象 obj = json.loads(data) 禁用ascii之后,将json对象转化为json格式字符串 html = json.dumps(obj, ensure_ascii=False) json 对象通过 str转换后 使用 utf-8 字符集格式写入 保存和之前的方法相同 with open('json.txt', 'w', encoding='utf-8') as f: f.write(html)
30.ajax请求自带的头部 'X-Requested-With':'XMLHttpRequest'
31.豆瓣默认都得使用https来进行抓取,所以需要使用ssl模块忽略证书 例: url = 'http://movie.douban.com/j/chart/top_list?type=24&interval_id=100%3A90&action=' page = int(input('请输入要获取页码:')) start = (page - 1) * 20 limit = 20 key = { 'start':start, 'limit':limit } key = urllib.parse.urlencode(key) url = url + '&' + key headers = { 'X-Requested-With':'XMLHttpRequest', 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36' } request = urllib.request.Request(url, headers=headers) # context = ssl._create_unverified_context() response = urllib.request.urlopen(request) jsonret = response.read() with open('douban.txt', 'w', encoding='utf-8') as f: f.write(jsonret.decode('utf-8')) print('over')
32.创建处理 http 请求的对象 http_handler = urllib.request.HTTPHandler()
33.处理 https 请求 https_handler = urllib.request.HTTPSHandler()
34.创建支持http请求的opener对象 opener = urllib.request.build_opener(http_handler)
35.创建 reponse 对象 例:opener.open(Request 对象) request = urllib.request.Request('http://www.baidu.com/') reponse = opener.open(request) 进行保存 with open('文件名.html', 'w', encoding='utf-8') as f: f.write(reponse.read().decode('utf-8'))
36.代理服务器 http_proxy_handler = urllib.request.ProxyHandler({'https':'ip地址:端口号'}) 例:http_proxy_handler = urllib.request.ProxyHandler({'https':'121.43.178.58:3128'})
37.私密代理服务器(下面的只是一个例子,不一定正确) authproxy_handler = urllib.request.ProxyHandler({"http" : "user:password@ip:port"})
38.不使用任何代理 http_proxy_handler = urllib.request.ProxyHandler({})
39.使用了代理之后的 opener 写法 opener = urllib.request.build_opener(http_proxy_handler)
40.response 写法 response = opener.open(request)
41.如果访问一个不存在的网址会报错 urllib.error.URLError
42.HTTPError(是URLError的子类) 例: try: urllib.request.urlopen(url) except urllib.error.HTTPError as e: print(e.code) print(e.reason) except urllib.error.URLError as e: print(e)
43.使用 CookieJar 创建一个 cookie 对象,保存 cookie 值 import http.cookiejar cookie = http.cookiejar.CookieJar( )
44.通过HTTPCookieProcessor构建一个处理器对象,用来处理cookie cookie_handler = urllib.request.HTTPCookieProcessor(cookie) opener 的写法 opener = urllib.request.build_opener(cookie_handler)
45.使用 r'\x' 消除转义 \d 表示转义字符 r'\d' 表示 \d
46.设置 正则模式 pattern = re.compile(r'规则', re.xxx ) pattern = re.compile(r'i\s(.*?),') 例:pattern = re.compile(r'LOVE', re.I)
使用 pattern 进行调用匹配 47.match 只匹配开头字符 pattern.match('字符串'[,起始位置,结束位置]) 例:m = pattern.match('i love you', 2, 6) 返回值为 <re.Match object; span=(2, 6), match='love'>
48. search 从开始匹配到结尾,返回第一个匹配到的 pattern.search('字符串') 例:m = pattern.search('i love you, do you love me, yes, i love') 返回值为 <re.Match object; span=(2, 6), match='love'>
49.findall 将匹配到的都放到列表中 pattern.findall('字符串') 例:m = pattern.findall('i love you, do you love me, yes, i love') 返回值为 ['love', 'love', 'love']
50.split 使用匹配到的字符串对原来的数据进行切割 pattern.split('字符串',次数) 例:m = pattern.split('i love you, do you love me, yes, i love me', 1) 返回值为 ['i ', ' you, do you love me, yes, i love me'] 例:m = pattern.split('i love you, do you love me, yes, i love me', 2) 返回值为 ['i ', ' you, do you ', ' me, yes, i love me'] 例:m = pattern.split('i love you, do you love me, yes, i love me', 3) 返回值为 ['i ', ' you, do you ', ' me, yes, i ', ' me']
51.sub 使用新字符串替换匹配到的字符串的值,默认全部替换 pattern.sub('新字符串','要匹配字符串'[,次数]) 注:返回的是字符串 例: string = 'i love you, do you love me, yes, i love me' m = pattern.sub('hate', string, 1) m 值为 'i hate you, do you love me, yes, i love me'
52.group 匹配组 m.group() 返回的是匹配都的所有字符 m.group(1) 返回的是第二个规则匹配到的字符 例: string = 'i love you, do you love me, yes, i love me' pattern = re.compile(r'i\s(.*?),') m = pattern.match(string) m.group() 返回值为 'i love you,' m.group(1) 返回值为 'love you'
53.匹配标签 pattern = re.compile(r'<div class="thumb">(.*?)<img src=(.*?) alt=(.*?)>(.*?)</div>', re.S)
54.分离出文件名和扩展名,返回二元组 os.path.splitext(参数) 例: 获取路径 image_path = './qiushi' 获取后缀名 extension = os.path.splitext(image_url)[-1]
55.合并多个字符串 os.path.join() 图片路径 image_path = os.path.join(image_path, image_name + extension) 保存文件 urllib.request.urlretrieve(image_url, image_path)
56.获取 a 标签下的 href 的内容 pattern = re.compile(r'<a href="(.*?)" class="main_14" target="_blank">(.*?)</a>', re.M)
57.href 中有中文的需要先进行转码,然后再拼接 smile_url = urllib.parse.quote(smile_url) smile_url = 'http://www.jokeji.cn' + smile_url
58.导入 etree from lxml import etree
59.实例化一个 html 对象,DOM模型 etree.HTML (通过requests库的get方法或post方法获取的信息 其实就是 HTML 代码) 例:html_tree = etree.HTML(text) 返回值为 <Element html at 0x26ee35b2400> 例:type(html_tree) <class 'lxml.etree._Element'>
60.查找所有的 li 标签 html_tree.xpath('//li')
61.获取所有li下面a中属性href为link1.html的a result = html_tree.xpath('//标签/标签[@属性="值"]') 例:result = html_tree.xpath('//li/a[@href="link.html"]')
62.获取最后一个 li 标签下 a 标签下面的 href 值 result = html_tree.xpath('//li[last()]/a/@href')
63.获取 class 为 temp 的结点 result = html_tree.xpath('//*[@class = "temp"]')
64.获取所有 li 标签下的 class 属性 result = html_tree.xpath('//li/@class')
65.取出内容 [0].text 例:result = html_tree.xpath('//li[@class="popo"]/a')[0].text 例:result = html_tree.xpath('//li[@class="popo"]/a/text()')
66.将 tree 对象转化为字符串 etree.tostring(etree.HTML对象).decode('utf-8')
67.动态保存图片,使用url后几位作为文件名 request = urllib.request.Request(url, headers=headers) response = urllib.request.urlopen(request) html_tree = etree.HTML(html) img_list = html_tree.xpath('//div[@class="box picblock col3"]/div/a/img/@src2') for img_url in img_list: # 定制图片名字为url后10位 file_name = 'image/' + img_url[-10:] load_image(img_url, file_name) load_image内容: def load_image(url, file_name): headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36', } request = urllib.request.Request(url, headers=headers) response = urllib.request.urlopen(request) image_bytes = response.read() with open(file_name, 'wb') as f: f.write(image_bytes) print(file_name + '图片已经成功下载完毕') 例: def load_page(url): headers = { #'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36', } print(url) # exit() request = urllib.request.Request(url, headers=headers) response = urllib.request.urlopen(request) html = response.read() # 这是专业的图片网站,使用了懒加载,但是可以通过源码来进行查看,并且重新写xpath路径 with open('7image.html', 'w', encoding='utf-8') as f: f.write(html.decode('utf-8')) exit() # 将html文档解析问DOM模型 html_tree = etree.HTML(html) # 通过xpath,找到需要的所有的图片的src属性,这里获取到的 img_list = html_tree.xpath('//div[@class="box picblock col3"]/div/a/img/@src2') for img_url in img_list: # 定制图片名字为url后10位 file_name = 'image/' + img_url[-10:] load_image(img_url, file_name) def load_image(url, file_name): headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36', } request = urllib.request.Request(url, headers=headers) response = urllib.request.urlopen(request) image_bytes = response.read() with open(file_name, 'wb') as f: f.write(image_bytes) print(file_name + '图片已经成功下载完毕') def main(): start = int(input('请输入开始页面:')) end = int(input('请输入结束页面:')) url = 'http://sc.chinaz.com/tag_tupian/' for page in range(start, end + 1): if page == 1: real_url = url + 'KaTong.html' else: real_url = url + 'KaTong_' + str(page) + '.html' load_page(real_url) print('第' + str(page) + '页下载完毕') if __name__ == '__main__': main()
68.懒图片加载案例 例: import urllib.request from lxml import etree import json def handle_tree(html_tree): node_list = html_tree.xpath('//div[@class="detail-wrapper"]') duan_list = [] for node in node_list: # 获取所有的用户名,因为该xpath获取的是一个span列表,然后获取第一个,并且通过text属性得到其内容 user_name = node.xpath('./div[contains(@class, "header")]/a/div/span[@class="name"]')[0].text # 只要涉及到图片,很有可能都是懒加载,所以要右键查看网页源代码,才能得到真实的链接 # 由于这个获取的结果就是属性字符串,所以只需要加上下标0即可 face = node.xpath('./div[contains(@class, "header")]//img/@data-src')[0] # .代表当前,一个/表示一级子目录,两个//代表当前节点里面任意的位置查找 content = node.xpath('./div[@class="content-wrapper"]//p')[0].text zan = node.xpath('./div[@class="options"]//li[@class="digg-wrapper "]/span')[0].text item = { 'username':user_name, 'face':face, 'content':content, 'zan':zan, } # 将其存放到列表中 duan_list.append(item) # 将列表写入到文件中 with open('8duanzi.txt', 'a', encoding='utf-8') as f: f.write(json.dumps(duan_list, ensure_ascii=False) + '\n') print('over') def main(): # 爬取百度贴吧,不能加上headers,加上headers爬取不下来 url = 'http://neihanshequ.com/' headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36', } request = urllib.request.Request(url, headers=headers) response = urllib.request.urlopen(request) html_bytes = response.read() # fp = open('8tieba.html', 'w', encoding='utf-8') # fp.write(html_bytes.decode('utf-8')) # fp.close() # exit() # 将html字节串转化为html文档树 # 文档树有xpath方法,文档节点也有xpath方法 # 【注】不能使用字节串转化为文档树,这样会有乱码 html_tree = etree.HTML(html_bytes.decode('utf-8')) handle_tree(html_tree) if __name__ == '__main__': main()
69. . / 和 // 在 xpath 中的使用 .代表当前目录 / 表示一级子目录 // 代表当前节点里面任意的位置
70.获取内容的示范 获取内容时,如果为字符串,则不需要使用 text 只需要写[0] face = node.xpath('./div[contains(@class, "header")]//img/@data-src')[0] div 下 class 为 "content-wrapper" 的所有 p 标签内容 content = node.xpath('./div[@class="content-wrapper"]//p')[0].text div 下 class 为 "options" 的所有 li 标签下 class为 "digg-wrapper" 的所有 span 标签内容 zan = node.xpath('./div[@class="options"]//li[@class="digg-wrapper"]/span')[0].text
71.将json对象转化为json格式字符串 f.write(json.dumps(duan_list, ensure_ascii=False) + '\n')
72.正则获取 div 下的内容 1.获取 div 到 img 之间的数据 2.img 下 src 的数据 3.img 下 alt 的数据 4.一直到 div 结束的数据 pattern = re.compile(r'<div class="thumb">(.*?)<img src=(.*?) alt=(.*?)>(.*?)</div>', re.S) pattern.方法 ,参考上面的正则
73.带有参数的 get 方式 import requests params = { 'wd':'中国' } r = requests.get('http://www.baidu.com/s?', headers=headers, params=params) requests.get 还可以添加 cookie 参数
74.设置编码 r.encoding='utf-8
75.查看所有头信息 r.request.headers
76.在 requests.get 方法中 url,params,headers,proxies 为参数 url 网址 params 需要的数据 headers 头部 proxies 代理
77.通过 Session 对象,发送请求 s = requests.Session() 78.发送请求 s.post(url,data,headers) 79.接收请求 s.get(url[,proxies]) 80.当返回为 json 样式时 例: city = input('请输入要查询的城市:') params = { 'city':city } r = requests.get(url, params=params) r.json() 会打印出响应的内容 81.BeautifulSoup 创建对象 from bs4 import BeautifulSoup soup = BeautifulSoup(open(url,encoding='utf-8),'lxml') 82.查找第一个<title> 标签 soup.title 返回值为 <title>三国猛将</title> 83.查找第一个 a 标签 soup.a 返回值为 <a class="aa" href="http://www.baidu.com" title="baidu">百度</a> 84.查找第一个 ul 标签 soup.ul 85.查看标签名字 a_tag = soup.a a_tag.name 返回值为 a 86.查看标签内容 a_tag.attrs 返回值为 {'href': 'http://www.baidu.com', 'title': 'baidu', 'class': ['aa']} 87.获取找到的 a 标签的 href 内容(第一个 a) soup.a.get('href') 返回值为 http://www.baidu.com 88.获取 a 标签下的 title 属性(第一个 a) soup.a.get('title') 返回值为 baidu 89.查看 a 标签下的内容 soup.标签.string 标签还可以是 head、title等 soup.a.string 返回值为 百度 90.获取 p 标签下的内容 soup.p.string 91.查看 div 的内容,包含 '\n' soup.div.contents 返回值为 ['\n', <div class="div"> <a class="la" href="www.nihao.com">你好</a> </div>, '\n', <div> <a href="www.hello.com">世界</a> </div>, '\n'] 92.查看使用的字符集 soup.div.contents[1] 返回值为 <meta charset="utf-8"/> 93.查看body的子节点 soup.标签.children 例:soup.body.children 返回值是一个迭代对象,需要遍历输出 返回值为 <list_iterator object at 0x0000021863886C10> for child in soup.body.children: print(child) 返回值为 body 中的所有内容 94.查看所有的子孙节点 soup.标签.descendants 例:soup.div.descendants 返回值为 <div class="div"> <a class="la" href="www.nihao.com">你好</a> </div> <a class="la" href="www.nihao.com">你好</a> 你好 95.查看所有的 a 标签 soup.find_all('a') 返回值为 包含所有的 a 标签的列表 96.查看 a 标签中第二个链接的内容 soup.find_all('a')[1].string 97.查看 a 标签中第二个链接的href值 soup.find_all('a')[1].href 98.将 re 正则嵌入进来,找寻所有以 b 开头的标签 soup.findall(re.compile('^b')) 返回值为 <body>标签 <b> 99.找到所有的 a 标签和 b 标签 soup.findall(re.compile(['a','b'])) 返回值为 <a> 和 <b> 标签 100.通过标签名获取所有的 a 标签 soup.select('a') 返回值为 所有的 <a> 标签 101.通过 类名 获取标签(在 class 等于的值前面加 .) soup.select('.aa') 返回值为 class='aa' 的标签 102.通过 id 名获取标签(在 id 等于的值前面加 #) soup.select('#wangyi') 返回值为 id='wangyi'的标签 103.查看 div 下 class='aa' 的标签 soup.select('标签 .class 等于的值') soup.select('div .aa') 104.查看 div 下,第一层 class='aa' 的标签 soup.select('.标签名 > .class= 的值') soup.select('.div > .la') 105.根据属性进行查找,input 标签下class为 haha 的标签 soup.select('input[class="haha"]') 例: import requests from bs4 import BeautifulSoup import json import lxml def load_url(jl, kw): headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36', } url = 'http://sou.zhaopin.com/jobs/searchresult.ashx?' params = { 'jl':jl, 'kw':kw, } # 自动完成转码,直接使用即可 r = requests.get(url, params=params, headers=headers) handle_data(r.text) def handle_data(html): # 创建soup对象 soup = BeautifulSoup(html, 'lxml') # 查找职位名称 job_list = soup.select('#newlist_list_content_table table') # print(job_list) jobs = [] i = 1 for job in job_list: # 因为第一个table只是表格的标题,所以要过滤掉 if i == 1: i = 0 continue item = {} # 公司名称 job_name = job.select('.zwmc div a')[0].get_text() # 职位月薪 company_name = job.select('.gsmc a')[0].get_text() # 工作地点 area = job.select('.gzdd')[0].get_text() # 发布日期 time = job.select('.gxsj span')[0].get_text() # 将所有信息添加到字典中 item['job_name'] = job_name item['company_name'] = company_name item['area'] = area item['time'] = time jobs.append(item) # 将列表转化为json格式字符串,然后写入到文件中 content = json.dumps(jobs, ensure_ascii=False) with open('python.json', 'w', encoding='utf-8') as f: f.write(content) print('over') def main(): # jl = input('请输入工作地址:') # kw = input('请输入工作职位:') load_url(jl='北京', kw='python') if __name__ == '__main__': main() 106.将字典进行 json 转换为 import json str_dict = {"name":"张三", "age":55, "height":180} print(json.dumps(str_dict, ensure_ascii=False)) 使用 ensure_ascii 输出则为 utf-8 编码 107.读取转换的对象,(注意 loads 和 load 方法) json.loads(json.dumps 对象) string = json.dumps(str_dict, ensure_ascii=False) json.loads(string) {"name":"张三", "age":55, "height":180} 108.将对象序列化之后写入文件 json.dump(字典对象,open(文件名.json,'w',encoding='utf-8,ensure_ascii=False)) json.dump(str_dict, open('jsontest.json', 'w', encoding='utf-8'), ensure_ascii=False) 109.转换本地的 json 文件转换为 python 对象 json.load(open('文件名.json',encoding='utf-8)) 110.jsonpath 示例: book.json文件 { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } } } import json import jsonpath obj = json.load(open('book.json', encoding='utf-8')) 所有book book = jsonpath.jsonpath(obj, '$..book') print(book) 所有book中的所有作者 authors = jsonpath.jsonpath(obj, '$..book..author') print(authors) book中的前两本书 '$..book[:2]' book中的最后两本书 '$..book[-2:]' book = jsonpath.jsonpath(obj, '$..book[0,1]') print(book) 所有book中,有属性isbn的书籍 book = jsonpath.jsonpath(obj, '$..book[?(@.isbn)]') print(book) 所有book中,价格小于10的书籍 book = jsonpath.jsonpath(obj, '$.store.book[?(@.price<10)]') print(book) 111.requests.get 方法的流程 r = requests.get('https://www.baidu.com/').content.decode('utf-8') 从状态码到 二进制码到 utf-8 编码 112.对 soup 对象进行美化 html = soup.prettify() <title> 百度一下,你就知道 </title> 113.将内容 string 化 html.xpath('string(//*[@])') 114.获取属性 soup.p['name'] 115.嵌套选择 soup.head.title.string 116.获取父节点和祖孙节点 soup.a.parent list(enumerate(soup.a.parents)) 117.获取兄弟节点 soup.a.next_siblings list(enumerate(soup.a.next_siblings)) soup.a.previous_siblings list(enumerate(soup.a.previous_siblings)) 118.按照特定值查找标签 查找 id 为 list-1 的标签 soup.find_all(attrs={'id': 'list-1'}) soup.find_all(id='list-1') 119.返回父节点 find_parents()返回所有祖先节点 find_parent()返回直接父节点 120.返回后面兄弟节点 find_next_siblings()返回后面所有兄弟节点 find_next_sibling()返回后面第一个兄弟节点。 121.返回前面兄弟节点 find_previous_siblings()返回前面所有兄弟节点 find_previous_sibling()返回前面第一个兄弟节点。 122.返回节点后符合条件的节点 find_all_next()返回节点后所有符合条件的节点 find_next()返回第一个符合条件的节点 123.返回节点前符合条件的节点 find_all_previous()返回节点前所有符合条件的节点 find_previous()返回第一个符合条件的节点 124.requests 的请求方式 requests.post(url) requests.put(url) requests.delete(url) requests.head(url) requests.options(url) 125.GET请求 response = requests.get(url) print(response.text) 126.解析 json response.json() json.loads(response.text) 127.发送 post 请求 response = requests.post(url, data=data, headers=headers) response.json() 128.文件上传 在 post 方法内部添加参数 files 字典参数 import requests files = {'file': open('favicon.ico', 'rb')} response = requests.post("http://httpbin.org/post", files=files) print(response.text) 129.获取 cookie response.cookie 返回值是 字典对象 for key, value in response.cookies.items(): print(key + '=' + value) 130.模拟登录 requests.get('http://httpbin.org/cookies/set/number/123456789') response = requests.get('http://httpbin.org/cookies') 131.带有 Session 的登录 s = requests.Session() s.get('http://httpbin.org/cookies/set/number/123456789') response = s.get('http://httpbin.org/cookies') 132.证书验证 urllib3.disable_warnings() response = requests.get('https://www.12306.cn', verify=False) response = requests.get('https://www.12306.cn', cert=('/path/server.crt', '/path/key')) 133.超时设置 from requests.exceptions import ReadTimeout response = requests.get("http://httpbin.org/get", timeout = 0.5) response = urllib.request.urlopen(url, timeout=1) 134.认证设置 from requests.auth import HTTPBasicAuth r = requests.get('http://120.27.34.24:9001', auth=HTTPBasicAuth('user', '123')) r = requests.get('http://120.27.34.24:9001', auth=('user', '123')) 135.异常处理 超时 ReadTimeout 连接出错 ConnectionError 错误 RequestException 136.URL 解析 from urllib.parse import urlparse result = urlparse('http://www.baidu.com/index.html;user?id=5#comment') result = urlparse('www.baidu.com/index.html;user?id=5#comment', scheme='https') result = urlparse('http://www.baidu.com/index.html;user?id=5#comment',allow_fragments=False) 136.urllib.parse.urlunparse data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment'] print(urlunparse(data)) http://www.baidu.com/index.html;user?a=6#comment 137.合并 url urllib.parse.urljoin urljoin('http://www.baidu.com', 'FAQ.html') http://www.baidu.com/FAQ.html urljoin('www.baidu.com#comment', '?category=2') www.baidu.com?category=2
matplotlib示例
plt.plot 内只有一个列表示例 import matplotlib.pyplot as plt lst = [4.53,1.94,4.75,0.43,2.02,1.22,2.13,2.77] plt.plot(lst) plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 plt.title("使用一行列表进行绘制折线图") plt.show()
import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 x = range(0,8) y1 = [4.53,1.74,4.55,0.03,2.12,1.22,2.43,2.77] y2 = [2.38, 4.23,1.49,2.75,3.73,4.90,0.13,1.29] plt.plot(x,y1,'b-1',x,y2,'m:o') plt.xlabel('x轴') plt.ylabel('y轴') plt.title("绘制两个折线图示例") plt.show()
设置显示样式 plt.plot(x,y1,'b-1',x,y2,'m:o')
设置中文标签 plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
import numpy as np import matplotlib.pyplot as plt with open("haidian.csv","r",encoding = 'utf-8') as f: data = np.loadtxt(f,str,delimiter = ',') x = data[:,1][::10] y = data[:,4][::10] plt.plot(x,y,'g-o') plt.xlabel("时间",fontproperties = 'SimHei') plt.ylabel("温度",fontproperties = 'SimHei') plt.title("海淀地区20日温度趋势图",fontproperties = 'FangSong',fontsize = 20) plt.xticks(rotation=90) # x 轴旋转角度 plt.show()
设置 x y 标签时,指定使用的字体 fontproperties = 'SimHei' plt.xlabel("时间",fontproperties = 'SimHei') plt.ylabel("温度",fontproperties = 'SimHei')
打开 csv 文件时,使用 np.loadtxt 进行读取 先使用 with open 打开文件,然后使用 np.loadtxt 进行读取 np.loadtxt(f,str,delimiter = ',') 提取过来的数据时 numpy.str_类型,使用时可以使用str进行转换 with open("haidian.csv","r",encoding = 'utf-8') as f: data = np.loadtxt(f,str,delimiter = ',')
直方图 hist 参数 data:必选参数,绘图数据 bins:直方图的长条形数目,可选项,默认为10 normed:是否将得到的直方图向量归一化,可选项 默认为0,代表不归一化,显示频数 normed=1 表示归一化,显示频率 facecolor:长条形的颜色 edgecolor:长条形边框的颜色 alpha:透明度
一张图显示两个直方图示例 from matplotlib import pyplot as plt x = [5,8,10] y = [12,16,6] x2 = [6,9,11] y2 = [6,15,7] plt.bar(x, y, align = 'center',label = 'x') plt.bar(x2, y2, color = 'g', align = 'center',label = 'x2') plt.title('直方图图示') plt.ylabel('Y轴') plt.xlabel('X轴') plt.legend() plt.show()
使用 plt.subplot(2,1) 绘制子图 通过子图设置标签 ax[0].hist(avg_wd,bins = 15,alpha=0.7) ax[0].set(title=u"时间和温度的关系图",ylabel=u"温度") # 设置标题 ax[1].hist(avg_sd,bins = 15,alpha=0.7) ax[1].set_title('时间和湿度的关系图') ax[1].set(title=u"14-28日烟台时间和湿度的关系图",ylabel=u"湿度") # 设置标题
matplotlib颜色线条及绘制直线
plt.axhline(y=0,ls=":",c="yellow")#添加水平直线 plt.axvline(x=4,ls="-",c="green")#添加垂直直线
matplotlib绘制子图
fig,subs = plt.subplots(2,2) subs[0][0].plot(data_math_C1) subs[0][0].set_title('C_1 曲线') subs[0][1].plot(data_math_C2) subs[0][1].set_title('C_2 曲线') subs[1][0].plot(data_math_C3) subs[1][0].set_title('C_3 曲线') subs[1][1].plot(data_math_C4) subs[1][1].set_title('C_4 曲线') plt.show()
下载数据到csv中(乱码),使用numpy , pandas读取失败 解决方案
读取数据,下载数据到 csv 文件中 allUniv 列表类型[[...],[...]] 字符集编码使用 utf-8-sig with open('文件名.csv','w',newline='',encoding='utf-8-sig') as fout: write = csv.writer(fout) columns = ['文字', '文字', '文字', '文字', '文字', '文字'] write.writerow(columns) for row in allUniv: write.writerow(row)
读取 csv 文件 一定要使用 pd.read_csv 进行读取 data = pd.read_csv('文件名.csv') print(data[:5])
查看一个数所有的因子及因子的和
def factor(n): nums = [ ] for i in range(1,n+1): if n % i == 0: nums.append(i) print(n,"的因子有:",nums) print("所有因子的和为: ",sum(nums)) while True: num = int(input("请输入 100 到 1000 之间的数")) if not 100 <= num <= 1000: print("请输入正确数值") continue factor(num) break
输入 1,2,4,5,78 返回 (1, 78, 2, 4, 5, 90) 返回形式:最小值 最大值 其余值 及 总和
def min_max_sum(num): num = list(num) Min = min(num) Max = max(num) Sum = sum(num) num.remove(Min) num.remove(Max) tup = [] tup.append(Min) tup.append(Max) for i in num: tup.append(i) tup.append(Sum) tup = tuple(tup) print(tup) return Min,Max,Sum num = tuple(int(i) for i in input().split(',')) min_max_sum(num)
1000以内能被3或5整除但不能被10整除的数的个数为 dic = {'0':0} for i in range(1000): if i % 3 == 0 and i %5 == 0 and i % 10 != 0: dic['0'] += 1 print("1000以内能被3或5整除但不能被10整除的数的个数为:",dic['0'])
输入数字判断是否是偶数,输出两个质数的和为该偶数的值 nums = [] lst = [i for i in range(101)] l = [] for j in range(2,101): # 将质数加入到 l 中 temp = 1 for i in range(2,j-1): if lst[j] % i == 0: temp = 0 if temp != 0: l.append(lst[j]) while True: num = int(input("输入 0 表示终止")) if num == 0: # 输入为 0 退出循环 break nums.append(num) for c in nums: if c % 2 == 0: # 如果为偶数 for i in l: # l 是质数的集合 if c - i in l: print("{}={}+{}".format(c, i, c - i)) break else: print("{0} is odd number!".format(c))
十进制转换为其他进制(不使用format)
base = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'), ord('A') + 6)] # ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] def dec2bin(string_num): '''十进制转换为 二进制''' num = int(string_num) # 转换为 整数 mid = [] while True: if num == 0: break # 如果输入的十进制为 0 则退出 num, rem = divmod(num, 2) # num 为 num / 2 的值 # rem 为 余数 mid.append(base[rem]) # 将余数添加到 mid 中 return ''.join([str(x) for x in mid[::-1]]) def dec2oct(string_num): '''转换为 八进制''' num = int(string_num) # 转换为 整数 mid = [] while True: if num == 0: break num, rem = divmod(num, 8) # num 为 num / 8 的值 # rem 为 余数 mid.append(base[rem]) # 将余数添加到 mid 中 return ''.join([str(x) for x in mid[::-1]]) def dec2hex(string_num): '''转换为 十六进制''' num = int(string_num) # 转换为 整数 mid = [] while True: if num == 0: break num, rem = divmod(num, 16) # num 为 num / 16 的值 # rem 为 余数 mid.append(base[rem]) # 将余数添加到 mid 中 return ''.join([str(x) for x in mid[::-1]]) num = float(input()) # 让用户输入数字 print(dec2bin(num),dec2oct(num),dec2hex(num)) # 输出 十进制转为 2 ,8 ,16 进制之后的数
字典元组列表常用方法
启发: 1.可以使用系统给出的方法,就不要自己去创建判断,效率可能会降低很多 2.使用一个变量不能解决问题,那就创建多个变量 3.找准数据类型,只要数据是这种数据类型,那么它就具有这个数据类型应该具有的方法,如果没有你需要的,那么就进行强制转换. 4.使用字典存储值,可以将两个序列对象的格式进行自定义 dict_xy = dict(zip(df['名称'],df['名称'])) # 将数据存为字典结构 for key,value in dict_xy.items(): # 对字典进行遍历 dict_xy[key] = float(value.split("亿")[0]) # 去掉多余数目 print(dict_xy)
matplotlib 设置x轴斜体 plt.xticks(rotation = 45)
sorted(字典名.items(), key=lambda x: x[1])
x = a[a['列名'] == 值]['列名'] y = a[a['列名'] == 值]['列名'] dic_xy = dict(zip(x,y)) lst_xy = sorted(dic_xy.items(), key=lambda x: x[1],reverse = True) print(lst_xy) dic = {} for index in range(10): dic[lst_xy[index][0]] = lst_xy[index][1] print(dic)
终于,我还是对自己的博客下手了 爬取自己博客曾经发布过的所有标题
import csv import requests from bs4 import BeautifulSoup # # for num in range(1,44): url = ' + str(num) response = requests.get(url) response.raise_for_status() response.encoding = response.apparent_encoding html = response.text soup = BeautifulSoup(html, "html.parser") try: for i in range(50): # print(soup.find_all('a',attrs={'class':'postTitle2'})[i].text.strip('\n').strip()) with open("博客园标题.txt", "a+") as f: f.write(soup.find_all('a',attrs={'class':'postTitle2'})[i].text.strip('\n').strip() + '\n') # 向文件写入内容 print("爬取结束,并存入文件") except: pass
获取列表中出现的值,并按降序进行排列
string = input().split() dic = {} for i in string: dic[i] = dic.get(i,0) + 1 dic = sorted(dic.items(), key=lambda x: x[1],reverse=True) for key,value in dic: print(key,":",value)
flask的第一次尝试
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return "Hello Flask" @app.route('/index') def index(): return "Hello Index" if __name__ == "__main__": # app.run() app.run(debug=True)
感悟: 从 flask 中导入 Flask 后, from flask import Flask 创建一个 app app = Flask(__name__) 使用的网页路径写在 @app.route(" 路径位置 ") 中 @app.route("/") 表示根路径 @app.route("/index") 表示 index 网页 在使用了路径之后,在路径的正下方加入 def 创建该路径对应的函数 def index(): return "Hello Index" return 后面的内容会返回到网页上 使用 app.run() 可以运行 if __name__ == '__main__': app.run(debug = True) 使用 debug 进行调试
条件表达式 ages = 20 ticketPrice = 20 if ages >= 16 else 10 count = 8 print( count if count % 10 == 0 else "不能被10整除") 成立条件时执行的语句 if 条件 else 不成立时执行的语句
安装fiddler 谷歌插件 移动 .crx 插件无法安装问题 解决方案: 修改后缀名为 .zip 文件 进行解压后,使用浏览器扩展程序加载已解压的文件进行扩展 添加插件
绘制折线图 import matplotlib.pyplot as plt plt.plot(x 列表数据, y 列表数据) 除了可以是列表数据之外 还可以是 pandas 库的 <class 'pandas.core.series.Series'> 类型 不可以是 字典.keys() 和 字典.values() 类型
绘制散点图 plt.scatter(x, y) x ,可以为列表类型,字典的键值 keys(),values() 类型 range对象及 Series类型 y 可以为列表类型,字典的键值 keys(),values() 类型 Series 类型 可以添加 颜色 和 标签 plt.scatter(x,y,color="g",label="标签") 使用 plt.legend() 显示图例
绘制柱状图 plt.bar(x,y) x 可以为 字典的键值对类型,列表类型,可以为 Series 数据类型 y可以为 字典的键值对类型,列表类型,可以为 Series 数据类型
绘制饼图 plt.pie( 值, labels= 名称, # 标签名称 shadow=True, # 阴影 autopct='%1.1f%%' # 显示 百分比 ) 值 可以是字典的键值对类型 .keys(),可以是列表类型, 名称 可以是字典的键值对类型 .values(),可以是列表类型,
绘制词云图 name = '' # 名称 lst = list(df['列名']) # 列名对应的元素的集合 for i in range(len(df)): name += lst[i] ls = jieba.lcut(name) txt = " ".join(ls) w = wordcloud.WordCloud(font_path=r'C:\Windows\Fonts\STXINWEI.TTF', width = 1000,height = 700,background_color = "white", ) w.generate(txt) w.to_file("词云图.png")
绘制盒图 使用 sns.boxplot(data = data) 进行绘制 import seaborn as sns import numpy as np sns.set_style("whitegrid") data = np.random.normal(size=(20, 6)) + np.arange(6) / 2 sns.boxplot(data=data)
绘制小提琴图 sns.violinplot(data) data 为 np.random.normal(size=(20, 6)) + np.arange(6) / 2 此处的 data 为 <class 'numpy.ndarray'> 数据类型
补充 : 折线图的绘制 plt.plot([0, 1], [0, 1], sns.xkcd_rgb["pale red"], lw=3) plt.plot([0, 1], [0, 2], sns.xkcd_rgb["medium green"], lw=3) plt.plot([0, 1], [0, 3], sns.xkcd_rgb["denim blue"], lw=3) 使用 sns.xkcd_rgb 进行选择线条的颜色
绘制地形图 x, y = np.random.multivariate_normal([0, 0], [[1, -.5], [-.5, 1]], size=300).T pal = sns.dark_palette("green", as_cmap=True) sns.kdeplot(x, y, cmap=pal);
补充 绘制柱状图 x = np.random.normal(size=100) sns.distplot(x,kde=False) x = np.random.gamma(6, size=200) sns.distplot(x, kde=False, fit=stats.gamma) x = np.random.gamma(6, size=200) sns.distplot(x, kde=False, fit=stats.gamma)
补充 绘制散点图 使用 sns.joinplot(x = '名称',y = '名称',data = 数据) mean, cov = [0, 1], [(1, .5), (.5, 1)] data = np.random.multivariate_normal(mean, cov, 200) df = pd.DataFrame(data, columns=["x", "y"]) sns.jointplot(x="x", y="y", data=df)
散点图扩展: sns.stripplot(x="day", y="total_bill", data=tips, jitter=True) sns.swarmplot(x="day", y="total_bill", data=tips) sns.swarmplot(x="day", y="total_bill", hue="sex",data=tips) sns.swarmplot(x="total_bill", y="day", hue="time", data=tips)
绘制 点图 sns.pointplot(x="sex", y="survived", hue="class", data=titanic) sns.pointplot(x="class", y="survived", hue="sex", data=titanic, palette={"male": "g", "female": "m"}, markers=["^", "o"], linestyles=["-", "--"]);
多层面板分类图 tips = sns.load_dataset("tips") sns.factorplot(x="day", y="total_bill", hue="smoker", data=tips) factorplot(x="day", y="total_bill", hue="smoker", data=tips, kind="bar") sns.factorplot(x="day", y="total_bill", hue="smoker", col="time", data=tips, kind="swarm") sns.factorplot(x="time", y="total_bill", hue="smoker", col="day", data=tips, kind="box", size=4, aspect=.5)
绘制热力图 sns.heatmap(数据) uniform_data = np.random.rand(3, 3) heatmap = sns.heatmap(uniform_data) 可以添加的属性为 vmin=0.2, vmax=0.5 center=0,linewidths=.5 annot=True,fmt="d" cbar=False,cmap="YlGnBu"
今日成果:爬取百度贴吧
''' 第一页 https://tieba.baidu.com/f?kw=python&ie=utf-8&pn=0 # 第二页 https://tieba.baidu.com/f?kw=python&ie=utf-8&pn=50 # 第三页 https://tieba.baidu.com/f?kw=python&ie=utf-8&pn=100 ''' from urllib.parse import urlencode # 导入解析模块 from urllib.request import Request,urlopen # Request 请求 , urlopen 打开 def get_html(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36' } request = Request(url,headers=headers) response = urlopen(request) # print(response.read().decode("gbk","ignore")) # 返回的是二进制数据 return response.read() def save_html(filename,html_bytes): with open(filename,'wb') as f: # 使用 wb 进行存储数据 f.write(html_bytes) def main(): base_url = 'https://tieba.baidu.com/f?ie=utf-8&{}' # 贴吧 url content = input("请输入要进行查询的内容:") # 要进行查询的内容 num = int(input("请输入要下载的页数:")) for pn in range(num): print("正在下载第{}页".format(pn + 1)) args = { 'kw':content, # 内容 'pn':pn * 50 # 页码 } args = urlencode(args) # 进行转码 html_bytes = get_html(base_url.format(args)) # 传递拼接后的 base_url 给 get_html 函数 filename = "第" + str(pn+1) + "页.html" # 下载到本地的文件名称 save_html(filename,html_bytes) if __name__ == '__main__': main()
urlopen方法 #coding=gbk from urllib.request import urlopen # urlopen 打开网页使用 url = 'https://www.baidu.com/' # 要进行访问的 URL response = urlopen(url) # 发送请求 print(response.getcode()) # 获取 HTTP 响应码 200 print(response.geturl()) # 获取访问的网址信息 https://www.baidu.com/ print(response.info()) # 获取服务器响应的HTTP请求头 info = response.read() # 读取内容 print(info.decode()) # 打印内容
Request 方法 request = Request(url = url,headers = headers) # 带着 ua 去请求信息 print(request.get_header("User-agent")) # 获取请求头信息 response = urlopen(request) info = response.read()
安装 fake_useragent 第三方库 查看 headers 信息 from fake_useragent import UserAgent ua = UserAgent() print(ua.chrome) # 打印谷歌浏览器 # print(dir(ua)) print(ua.ie) # 打印 IE 浏览器 print(ua.firefox) # 打印火狐浏览器
使用 get 请求 from urllib.request import urlopen,Request from urllib.parse import quote # urlopen 打开网页使用 # Request 请求对象,带有 ua headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36' } url = 'https://www.baidu.com/s?wd={}'.format(quote('瀚阳的小驿站')) # 要进行访问的 URL , 使用 quote 进行转码 # 使用 urllib.parse 中的 urlencode 和 quote 方法 进行转码 # quote('瀚阳的小驿站') 进行转码 '%E7%80%9A%E9%98%B3%E7%9A%84%E5%B0%8F%E9%A9%BF%E7%AB%99' request = Request(url,headers = headers) # 进行请求 response = urlopen(request) print(response.read().decode())
from urllib.request import urlopen,Request from urllib.parse import urlencode from fake_useragent import UserAgent # urlopen 打开网页使用 # Request 请求对象,带有 ua # 使用 urlencode 对字典元素进行转换编码 args = { 'wd':"瀚阳的小驿站", "ie":"utf-8" } headers = { 'User-Agent': UserAgent().random } url = 'https://www.baidu.com/s?wd={}'.format(urlencode(args)) print(url) request = Request(url , headers = headers) response = urlopen(request) info = response.read() print(info.decode())
map,reduce,filter基础实现
#coding=gbk from operator import add # 导入加法 # map 函数名 , 序列对象 print(list(map(str,range(5)))) print(list(map(len,['abc','1234']))) # [3, 4] for num in map(add,range(3),range(1,4)): # 对 0+1 , 1+2 , 2+3 print(num) from functools import reduce from operator import add,mul,or_ seq = range(1,10) # 1~9 的所有元素 print(reduce(add,seq)) # 连加,seq 中的每一个元素 print(reduce(mul,seq)) # 连乘,seq 中的每一个元素 seq = [{1},{2},{3},{4},{5}] print(reduce(or_,seq)) # 将 seq 中的元素并集在一起,or_ seq = ['abcd','1234',',.?!',''] print(list(filter(str.isdigit,seq))) # 只保留元素全是数字的 print(list(filter(str.isalpha,seq))) # 只保留元素全是字母的 print(list(filter(None,seq))) # 保留等价于 True 的元素 gen = (2 ** i for i in range(5)) for i in gen: print(i,end = ' ') print() x,y,z = map(int,'123') print(x,y,z)
数据分析小题 DataFrame对象是一个表格型的数据结构 DataFrame对象的列是有序的 DataFrame对象列与列之间的数据类型可以互不相同 文件写操作时,writelines方法的参数可以是列表 元组 字典 wordcloud.WordCloud()函数中的参数mask是用来设置 词云的遮罩形状 pandas提供了对各种格式数据文件的读取和写入工具,其中包括 CSV文件 文本文件 工作簿文件 requests库的get()函数执行后会返回一个Response类型的对象,其text属性以 字符串 形式存储响应内容。 在matplotlib子图绘制中,若执行plt.subplot(3,2,4),则当前的绘图子区域索引号是 4 创建3*3单位矩阵 A=np.eye(3) jieba.cut(s)函数分词功能 精确模式分词 data1=np.loadtxt('data_txt.txt') 将文本文件“data_txt.txt”读取到数组data1中 matpltlib中绘制图形,通过更改绘图框的尺寸来设置相等的缩放比例的参数 scale import numpy as np Array1 = np.linspace(1,5,3,dtype=int) print(Array1) [1 3 5] 在python中,获取当前工作目录可以通过 os 库的getcwd函数获取 如果想返回DataFrame的所有列的平均值,可以使用 mean 统计函数 numpy的ndarray中的维度称为 轴 pandas中实现表格型数据集的对象是 DataFrame 试图将句子最精确地切开,适合文本分析的分词模式叫做 精确 模式分词 使用transpose函数可以实现numpy数组按轴进行转置 s=pd.Series([1,2,3,4]),则np.sqrt(s)是对s中的每一个数值求平方根 CSV文件本质上也是文本文件,可以用记事本或者excel打开。 带有else子句的异常处理结构,如果不发生异常则执行else子句中的代码 wordcloud.WordCloud()函数中的参数max_words 设置要显示的词的最大个数
求最大公约数最小公倍数 #coding=gbk import math m = int(input()) n = int(input()) print(math.gcd(m,n)) # 最大公约数 print((m*n)//math.gcd(m,n)) # 最小公倍数 将字符串 s="alex" 转换成列表 list(s) 不能使用 del 删除集合中的部分元素 组合数据类型的分类 序列类型、集合类型、映射类型 简述列表在实现基本数据同时发挥的重要作用 1)列表是一个动态长度的数据结构,可以根据需求增加或减少元素。 2)列表的一系列方法或操作符为计算提供了简单的元素运算手段。 3)列表提供了对每个元素的简单访问方式及所有元素的遍历方式 请列出5条写出优美代码的编程原则 (1) 清晰明了,规范统一; (2) 逻辑简洁,避免复杂逻辑; (3) 接口关系要清晰; (4) 函数功能扁平,避免太多层次嵌套; (5) 间隔要适当,每行代码解决适度问题
matplotlib 去掉坐标轴 #去掉x轴 plt.xticks([]) #去掉y轴 plt.yticks([]) #去掉坐标轴 plt.axis('off')
关于这学期的总结
# 例1-2 正确缩进 # 比较两个数字对于π的精度,保持缩进一致 pie = 3.1415 pie1 = 3.14 # 同一代码块内各行缩进空格数目相同,观察输出结果 if pie > pie1: print('π取pie更精确') elif pie == pie1: print('π取pie或pie1一样精确') else: print('π取pie1更精确') # 例1-4 长语句换行 # 给出3种水果的价格,计算总价 apple_price, banana_price, pear_price = 1, 1.5, 0.5 # 通过反斜杠实现长语句换行 total_price = apple_price + \ banana_price + \ pear_price print('total_price =', total_price) # 例1-5 逗号换行 # 方括号内,在逗号后直接换行 total_price = sum([apple_price, banana_price, pear_price]) print('total_price =', total_price) # 例1-6 分号隔离 # 给出3种水果的价格,计算总价 apple_price = 1; banana_price = 1.5; pear_price = 0.5 total_price = apple_price + banana_price + pear_price print('total_price =', total_price) import keyword print('Python中的所有保留字为:\n',keyword.kwlist) # 例1-8 赋值的基本形式 # 使用等号直接给num_int赋值一个整数值 num_int = 1 print('使用等号创建的整数为:', num_int) # 使用等号直接给num_float赋值一个浮点数值 num_float = 9.9 print('使用等号创建的浮点数为:', num_float) # 使用等号直接给string赋值一个字符串 string = 'python' print('使用等号创建的字符串为:', string) # 例1-9 序列赋值 # 序列赋值可给变量赋值多种数据类型 num_int, string, list1 = 123, 'str', [4,6] print('赋值创建的多种数据类型为:', num_int, string, list1) # 序列赋值可给变量赋值已赋值的变量 num1, num2, num3 = 7, 8, 9 num_int1, num_int2, num_int3 = num1, num2, num3 print('变量赋值为已赋值变量结果为:', num_int1, num_int2, num_int3) # 例1-10 链接赋值 str1 = str2 = str3 = 'STR' print('str1, str2, str3分别为:', str1, str2, str3) print('str1, str2, str3的内存地址分别为:', id(str1), id(str2), id(str3)) print('str1, str2, str3是否等价:', str1 is str2 is str) # 代码1-11 增量赋值 x = 100 x += 10 print('x += 10等价于x=x+10,其值为:', x) # 例1-12 算术运算 num_int = 4 num_float = 4.0 print('整数与浮点数的和为:', num_int + num_float) print('整数与浮点数的差为:', num_int - num_float) print('整数与浮点数的积为:', num_int * num_float) print('浮点数与整数的商为:', num_float / num_int) print('浮点数对整数取模结果为:', num_float % num_int) print('浮点数的整数次幂为:', num_float ** num_int) # 例1-13 赋值运算 num_int1 = 4 print('赋值后num_int1为:', num_int1) num_int1 = 4 + 6 print('赋值后num_int1为:', num_int1) num_int1 = 4 * 2 print('赋值后num_int1为:', num_int1) num_int1 = 4 / 2 print('赋值后num_int1为:', num_int1) num_int1 = 4 % 2 print('赋值后num_int1为:', num_int1) num_int1 = 4 ** 2 print('赋值后num_int1为:', num_int1) # 例1-14 比较运算 num_int = 4 num_float = 4.0 print('num_int与num_float是否相等:', num_int == num_float) print('num_int与num_float是否不相等:', num_int != num_float) print('num_int是否大于num_float:', num_int > num_float) print('num_int是否小于num_float:', num_int < num_float) print('num_int是否大于等于numfloat:', num_int >= num_float) print('num_int是否小于等于num_float:', num_int <= num_float) # 例1-15 逻辑运算 num_bool1 = False num_bool2 = True print('num_bool1 and num_bool2返回值为:', num_bool1 and num_bool2) print('num_bool1 or num_bool2返回值为:', num_bool1 or num_bool2) print('not num_bool2的返回值为:', not (num_bool2)) # 例1-16 身份运算 num_int1 = 15 num_int3 = 15 print('num_int1与num_int3储存单位是否相同:', num_int1 is num_int3) num_int2 = 15.0 print('num_int1与num_int2储存单位是否相同:', num_int1 is num_int2) # 如果储存单位相同就返回True,否则返回False print('num_int1与num_int3储存单位是否不同:', num_int1 is not num_int3) print('num_int1与num_int2储存单位是否不同:', num_int1 is not num_int2) # 例1-17 成员运算 num_int1 = 15 list2 = [1, 'apple', 15] print('num_int1是否在list2中:', num_int1 in list2) array = ('orange', 6, 15) print('num_int1是否不在array中:', num_int1 not in array) # 例1-18 运算符优先级 # 先执行乘除法运算,再执行加减法运算 print('num_float + num_int1 / num_int3 =', num_float + num_int1 / num_int3) # 先执行加减法运算,再执行比较运算 print('num_int1 - num_int2 > num_int1 - num_int3:', num_int1 - num_int2 > num_int1 - num_int3) # 先执行加减法运算,再做身份判断 print('num_int1 - num_int3 + num_int1 is num_int1:', num_int1 - num_int3 + num_int1 is num_int1) # 先执行指数运算,再执行减法运算,最后做身份判断 print('num_float ** 2 - 1 is not num_int2:', num_float ** 2 - 1 is not num_int2) #例1-19 创建 number num_int = 2 num_float = 4.5 num_bool = True num_complex = 3j print('数据类型分别为:\n', type(num_int), type(num_float), type(num_bool), type(num_complex)) # 例1-20 number 类型装换与混合运算 # number类型转换, 将float转换为int(直接去掉小数部分) print('int(4.5)的结果为:', int(4.5)) # 将int转换为float(直接增加小数部分) print('float(4)的结果为:', float(4)) # 将int和float转换为complex(直接增加虚部) print('complex(4)和complex(4.5)的结果分别为:', complex(4), complex(4.5)) # 不同number类型混合运算, int + float = float print('整数和浮点数和的类型为:', type(124 + 4.0)) # int + complex = complex print('整数和复数和的类型为:', type(124 + 5.3j)) # float + complex = complex print('浮点数和复数和的类型为:', type(4.0 + 5.3j)) # 例1-21 str 索引 string = "ilovePython" # 下标为正数,从第2个字符开始索引,到第5个字符 print('ilovePython[1:5] =', string[1:5]) # 下标为负数,从倒数第10个字符开始索引,到倒数第6个字符 print('ilovePython[-10:-6] =', string[-10:-6]) print('ilovePython[:5] =', string[:5]) # 尾下标留空,从第2个字符开始索引,到最后一个字符截止 print('ilovePython[1:] =', string[1:]) # 按步索引,从第2个元素开始索引,到第11个元素,步距为3 print('ilovePython[1:10:3] =', string[1:10:3]) # 例1-22 str 查询方法 print('string中n的位置和总数分别为:', string.index('n'), string.count('n')) print('string中是否只包含字母:', string.isalpha()) print('string中是否只包含数字:', string.isdigit()) print('string是否已P开头:', string.startswith('P')) print('string是否是标题化的:', string.istitle()) # 例1-23 str 改写方法 print('string左对齐填充至20个字符结果为:', string.ljust(20)) print('string右对齐填充至20个字符结果为:', string.rjust(20)) print('string大写化结果为:', string.upper()) print('string大小写置换结果为:', string.swapcase()) print('string中h替换为H结果为:', string.replace('h','H')) # 例1-24 str 方法-其他 # 以指定格式编码 string = string.encode('UTF-16', 'strict') print ("string编码为:", string) # 以指定格式解码 string = string.decode('UTF-16', 'strict') print ("string解码为:", string) # 以指定分隔符分割str print(string.partition(".")) string1 = ('I','love','Python') sep = '-' # 以sep为分隔将string1合并为新的字符串 print('以sep分隔合并string1为:', sep.join(string1)) # 例1-25 str 转义与常用操作 print ('\note\mybook') # str中包含\n,识别为换行符并转义 print ('\title\mybook') # str中包含\t,识别为制表符并转义 print (r'\note\mybook ') # 使用r制止转义 print (string + "TEST") # 输出连接的str print (string * 2) # 输出str两次 # 例1-26 创建 list # 使用方括号创建一个非空list list1 = ['runoob', 786, 2.23, 'john'] print('方括号建立的列表为:', list1) #建立元组 tuple1 = (123, 'xyz', 'zara', 'abc') list2 = list(tuple1) print('元组转换成列表结果为:', list2) # list函数将str拆开,作为新list中的元素 list3 = list('china') print('字符串转换成列表结果为:', list3) # 例1-27 list 基本操作 print('列表按指定长度索引结果为:', list3[-4:-2]) print('列表按步长索引结果为:', list3[0::2]) list1[2] = 666 print('列表替换结果为:', list1) print('list1和list2用+连接结果为:', list1 + list2) print('列表通过*重复结果为:', list1 * 2) # 例1-28 list 常用方法 print('list3中a出现的次数:', list3.count('a'), '\n', 'list3中a首次出现的位置:', list3.index('a')) list3.insert(0,'g') list1.append('新增') list2.extend(list3) print('在列表指定位置插入元素:', list3, '\n', '在列表末尾新增元素:', list1, '\n', '将list3扩展至list2:', list2) list3.insert(0,'g') list1.append('新增') list2.extend(list3) print('在列表指定位置插入元素:', list3, '\n', '在列表末尾新增元素:', list1, '\n', '将list3扩展至list2:', list2) list3.pop(0) list1.remove('新增') print('使用pop删除指定位置的元素:', list3, '\n', '使用remove删除指定元素:', list1) list2.pop(0) list2.sort() list3.reverse() print('列表排序:', list2, '\n', '列表反向排序:', list3) # 例1-29 创建tuple # 使用圆括号创建tuple tup1 = ('Google', 'Runoob') print('查看tup1类型:', type(tup1), '\n', '查看tup1:', tup1) # 不加括号创建tuple tup2 = "a", "b", "c", "d" print('查看tup2:', tup2, '\n', '查看tup2类型:', type(tup2)) # 将[‘x',’y',’z']转换成tuple tup3 = tuple(['x','y','z']) print('查看tup3:', tup3, '\n', '查看tup3类型:', type(tup3)) # 单个数字元素加逗号,变量是tuple tup4 = (50,) # 单个数字元素无逗号,变量是int tup5 = (50) print('tup4和tup5的类型分别为:', type(tup4), type(tup5)) # 例1-30 tuple 基本操作 print('tup2中第3元素为:', tup2[2]) print('tup2中第1个到倒数第二个元素为:', tup2[:-1]) print('连接两个元组结果为:', tup1 + tup2) print('元组重复输出结果为:', tup3 * 2) # 例1-31 tuple 内置方法 print('tup2中元素a出现的次数:', tup2.count('a')) print('tup2中元素a首次出现的位置:', tup2.index('a')) # 例1-32 创建 dict # 使用花括号创建空dict,更新键值对 dict1 = {} dict1['one'] = "This is 1" dict1['two'] = "This is 2" print('查看字典:', dict1) # 使用dict函数创建dict,指定键值对 dict2 = dict(name='小明', height=187) print('查看字典:', dict2) # 例1-33 print('通过键索引字典元素:', dict1['one']) dict1['one'] = 'this is 1' print('以键改字典元素值:', dict1) dict1[3] = 'This is 3' print('更新后的字典为:', dict1) del dict1[3] print('删除键3后的字典为:', dict1) # 例1-34 dict 内置方法 print('输出dict1中所有键值对:', dict1.items(), '\n', '输出dict1中所有的键:', dict1.keys(), '\n', '输出dict1中所有的值:', dict1.values()) print('与one对应的元素为:', dict1.get('one'), dict1.setdefault('one')) dict1.update(dict2) dict3 = dict2.copy() print('将dict2中键值对更新到dict1中:', dict1, '\n', '将dict2中内容复制到新的字典中:', dict3) dict1.pop('name') dict2.popitem() dict3.clear() print('删除dict1中name键对应的内容:', dict1, '\n', '随机删除dict2中的一个键值对为:', dict2.popitem(), '\n', '清空dict3中的内容:', dict3) # 例1-35 创建 set # 使用非空的{}创建set set1 = {1, 2, 3} print('set1的类型为:', type(set1)) # 创建一个空的set只能使用set函数 set2 = set() print('查看set2:', set2, '\n', 'set2的类型为:', type(set2)) # 将list、tuple转换为set set3 = set([1,2,3]) set4 = set((1,2,3)) print('查看set3和set4:', set3, set4, '\n', 'set3和set4的类型分别为:', type(set3), type(set4)) # 例1-36 set 常用方法 set1.add('a') print('add方法向set1中添加元素结果为:', set1) set1.pop() print('pop方法删除set1中任意一个元素结果为:', set1) set2.clear() print('清除set2中内容结果为:', set2) # 例1-37 set 集合运算 print('set4是否为set1的子集:', set4 < set1) print('set4和set1的并集为:', set4 | set1) print('set4和set1的交集为:', set4 & set1) print('set4和set1的差集为:', set4 - set1) # # 例1-38 输入不同数据类型 # # 输入一个数字,由Python默认类型 # number1 = input('请输入一个数字:') # # 输入一个str,由Python默认类型 # str1 = input('请输入一个字符串:') # # 输入一个数字,并将其转换为int类型 # number2 = int(input('请输入一个数字:')) # # 查看以上输入的输出结果类型 # print('number1、str1和number2的类型分别为:\n', # type(number1), type(str1), type(number2)) # 例1-39 print 函数应用 # print函数接受多个str print('我', '爱', '中华') # print函数在打印前计算结果 print('100+200 =', 100 + 200) # 例1-40 “ % + 格式符” 格式化输出 # 用%s、%d分别格式化字符串'Zara'和整数20 print("我的名字叫做%s,已经%d岁了!"%('Zara',20)) # 用%d格式化16,用%o将十进制整数16用八进制数表示 print("%d 的八进制是 %o"%(16,16)) # 用%.3f将整数转化为保留小数点后3位的float print("23 转化为保留3位小数的浮点数%.3f"%(23)) # format函数不带参数情况下的输出 print("我的名字叫做{},已经{}岁了!".format('Zara', 18)) # format函数带数字编号并打乱顺序 print("我的名字叫做{1},已经{0}岁了!".format(18, 'Zara')) # format函数带关键字参数 print("我的名字叫做{name},已经{age}岁了!".format(age=18,name='Zara')) # format函数格式化数字为二进制数 print("我的名字叫做{},已经{:b}岁了!".format('Zara', 18)) # # 例1-41 read 函数读取 test.txt 文件 # # 以只读模式打开test.txt文件 # data = open('../data/test.txt', 'r') # # 读取文件中的内容,存到content变量中 # content = data.read() # # 打印出content变量中包含的文本内容 # print('该文本中的内容是:', content) # #例1-42 write 函数写入文件 # # 打开一个文件 # web = open('../data/web.txt', 'w') # # 转换内容,写入文件 # value = ('http://www.tipdm.org', 14) # str_value = str(value) # web.write(str_value) # web.close() # # 打开文本,读取出写入的内容 # web = open(‘../data/web.txt', 'r') # content = web.read() # print('该文本中的内容是:', content) # # 例1-43 if-else语句实现登录界面 # name = input ('请输入用户名:') # password = input ('请输入密码:') # if name == "Lucy" and password == "123456": # print ('****登录成功,欢迎!*****') # else: # print ('-----您的输入有误,登录失败!-----') # # 例1-44 使用if-elif-else语句实现年龄段的判断 # age = input('请输入您的年龄:') # age = int(age) # if age < 18: # print('未成年人!') # elif age >= 18 and age <= 25: # print('青年人!') # elif age > 25 and age <= 60: # print('中年人!') # else: # print('老年人!') # #例1-45 嵌套if-elif-else语句 # age = input('请输入你的年龄:') # age = int(age) # if age == 35: # nation = input('请输入你的国籍:') # if nation == '英国': # print('你是Tom! ') # elif (nation == '法国'): # print('你是Frank! ') # else: # print('你是Bob! ') # elif age == 21: # print('你是Jane,来自南非! ') # elif age == 51: # print('你是Washington,来自澳大利亚! ') # else: # print('请输入正确年龄值! ') # 例1-46 if-else语句的单行形式 num1, num2 = 11, 90 print('num1加num2为百分数') if 1000 > num1 + num2 >100 else print('num1加num2不为百分数') # 例1-47 for语句遍历提取str # 单纯遍历的for语句 names = ['Michael', 'Bob', 'Tracy'] # 遍历输出names中的元素 for name in names: print(name) #例1-48 for语句遍历查询dict dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4} # 遍历键值对 print('\nkey_value:', end = '') for key, value in dic.items(): print(key, value, sep = ':', end = ' ') # 遍历键 print('\nkeys:', end = '') for key in dic.keys(): print(key, end = ' ') # 遍历值 print('\nvalues:', end = '') for value in dic.values(): print(value, end = ' ') # # 例1-49 嵌套for语句 # students = ['小明', '小红'] # subjects = ['语文', '数学'] # sum1 = [] # avg = [] # for i in students: # print ('开始录入%s的考试成绩!'%i) # sum = 0 # for j in subjects: # print('请输入%s成绩:'%j) # score = int(input()) # sum += score # average = sum / 2 # avg.append(average) # sum1.append(sum) # print(students, '的总分依次是', sum1, ',', '平均分依次是', avg) # print('完成成绩录入!') # 例1-50 while语句 sum = 0 n = 99 while n > 0: sum += n n -= 2 print(sum) # # 例1-51 嵌套while语句 # j = 1 # while j <= 2: # sum = 0 # i = 1 # name = input('请输入学生姓名:') # while i <= 2: # print ('请输入第%d门的考试成绩: '%i) # sum += int(input()) # i += 1 # avg = sum / (i-1) # print(name, '的平均成绩是%d'%avg) # j += 1 # print('学生成绩输入完成!') # 例1-52 break语句的使用 # break语句用于for循环 string = "Python" for i in string: # 遍历至string中的字符n时,不再执行else代码块 if i == 'n': break else: print("letter:{}". format(i)) # break语句用于while循环 counts = 0 while True: print(counts) counts += 1 # 满足counts等于3时跳出循环,不再进入循环体 if counts == 3: break # 例1-53 # 第一层循环,遍历次数为2 for i in range(2): print("-----%d-----" %i) # 第二层循环,遍历次数为5 for j in range(5): # 当j等于2或4时,不执行循环体 if j == 2 or j == 4: continue print(j) # 例1-54 for element in "Python": # element为y时,不做任何操作,不会被输出 if element == "y": pass else: print(element) counts = 0 while counts < 5: counts += 1 # i=3时,不执行循环体 if counts == 3: pass else: print(counts ** 2) # 例1-55 vec = [-4, -2, 0, 2, 4] # 用vec中元素的倍数,创建一个数组 print([x * 2 for x in vec]) # 创建一个包含2元tuple的list print([(x, x ** 2) for x in range(6)]) # 例1-56 list1 = [1, 2, 3, 4] # bytes函数、bytearray函数 print('list1的不可变字节数组为:', bytes(list1), '\n', 'list1的可变字节数组为:', bytearray(list1)) # chr函数、ord函数 print('整数40的unicode字符为:', chr(40), '\n', 'unicode字符(对应的整数为:', ord('(')) # bin函数 print('整数40的二进制形式为:', bin(40)) # ascii函数 print('字符串tipdm的ascii码为:', ascii('tipdm')) # hash函数 print('字符串tipdm的hash值为:', hash('tipdm')) # 例 1-57 # max函数、min函数 print('序列中的最大数为:', max(list1), '\n', '序列中的最小数为:', min(list1)) # abs函数 print('-10和100的绝对值分别为:', abs(-10), abs(100)) # pow函数 print('3的6次方为:', pow(3, 6)) # round函数 print('3.2四舍五入结果为:', round(3.2)) # divmod函数 print('7除以3的商和余数分别为:', divmod(7, 3)) #例 1-58 # map函数 # 对一个list中的各个float分别四舍五入 print('浮点数的四舍五入结果为:', list(map(round, [1.1, 2.2, 3.3, 4.4, 5.5