python
python 文件 .py
布尔型 True OR False
整形 浮点型 字符串
对象类型是不可变的,必须取名字
变量需要赋值
变量只能包含字母,下划线,数字。(但数字不能放开头)
除法:
-
正常除数 /
-
取整数 //
-
取余数%
幂指数:**
布尔型中 true =1 flase =0
自增 a++ += *= -=
type (a) 判断类型
true 与flase 会强制转换数据类型
字符串
可使用' ',与""
print只是去掉最外层的引号
布尔型中当内部为非空字符串时输出为True,当内部为空字符串时输出为Flase
\n 代表换行符
\t 代表制表符 相当于table
\代表转义字符,一次输出减少一个
拼接字符串 + 即可实现
字符串复制 字符串乘一个数字即可
字符串切片
str[i-1]代表第i位的字符
str[-i]代表倒数第i位的字符
切片是不能赋值,字符串是不可变的
str[0:2]取一段,前包括后不包括
切片隔一个切一个
str[0:4:2]以步长为2进行切片
取奇数位的 str[::2]
反转字符串[::-1]
-
len() 字符串长度
len(eng)
-
spilt()分割 默认不填以空格分隔
eng.split('g')
-
strip() 去掉多余的符合
eng.strip('.')
-
upper() 变成大写
-
lower() 变成小写
-
title() 单词首字母大写
eng.upper() eng.lower() eng.title() eng.capitalize() //句子首字母大写
-
join() 合并
a=eng.split('g') ' '.join(a)
-
replace() 替代
eng.replace('a','boy')
-
find()指定的数字出现在第几行
eng.find('f') 左起 eng.rfind('f') 右起
-
count()计数出现多少个字母
eng.count('s')
-
startswith()判断是否以什么开头,或者结尾
eng.startswith('a')
-
endswith()
列表
切片与字符串类似
列表修改,列表取值
对一个片段进行赋值
a[:2]=[1000,2000] a
列表合并
b=[1,2,3] a+b
a.extend(b) a//不创建,在a上修改
列表的添加
b.append(4) b
列表元素删除,不填默认最后一位,括号内填指定元素
b.pop(2) b b.pop() b
del 删除指定位置的元素
remove()删除某个元素
insert()插入某个元素
a.remove('zhang') a del a[0] a a.insert(3,'libai') a
列表元素的判断使用in 返回布尔型
2000 in a
列表升序或降序
c=[3,2,5,1,45] c.sort() c //升序 len(c) 长度判断
判断出现的次数
a.count(3)
判断出现的位置的位数
a.index(3)
字典
创建基本结构
dic={'li':1,'mu':2} dic
将双值子序列转化为字典
list=['ab','cd'] dict(list)
其格式为{key:value},字典是无序的
-
字典数据的添加
dic['c']=3 dic
-
修改
dic['c']=20 dic
-
合并
dic_2={'d':5,'e':6} dic.update(dic_2) dic
-
删除
del dic['d'] dic dic.clear() dic //清空
判断是否在字典中,只是判断字典中的key,同时必须保证字典是唯一的
'a' in dic_2 不存在返回一个布尔值
dic_2.get('a') 不存在返回一个空值 dic_2.get('a',0)
返回所有的key与values
dic_2.keys() dic_2.values() dic_2.items() //返回所有的键值对
迭代器
list(dic_2.keys())
集合
集合舍弃了值,只剩下key的字典
set_1=set() type(set_1) set_1={'a','b','c'} set(['a','b','c'])
集合是无序的,集合中的元素是唯一的
lis=['a','b','b','c'] lis set(lis)
可使用in是否在这个集合中
'a' in set_1
判断集合是否有交集
set_2={'c','df'} set_1&set_2
集合并集
set_1|set_2
找出在集合1中包含在集合2中不包含的数据
set_1-set_2
集合添加数据
set_1.update('e') set_1 set_1.update(set_2) set_1
元组和集合
元组也是由任意类型元素组成的序列
元组是不可变的
创建元组
tuple_1=(1,2,3) tuple_2=1,2,3 tuple_2 tuple_3=(5,) 创建一位元组 tuple_4=() tuple_4 创建一个空元组
a,b,c=tuple_1 元组的解包 a,b=b,a
将集合转变成元组
tuple(lis)
字典转化为元组
tuple(dic_2) 只是将其中的key提取出来
输入输出结构
name=input('what is your name\n') print('hi\t'+name)
name=input('what is your name\n') color=input('what is your favorite color\n') print('hi\t'+name+',you must be like '+color)
年龄判断
birth_year=input('birthday:') year=int(birth_year) age=2020 - year print(age) 注意减法运算不能在不同的数据类型中运算
体重判断
weight=input("how much gram are you") kilogram=2.0*int(weight) print("your kilogram is "+str(kilogram))
动态在两个字符串直接插入值
first='john' last='smith' message=f'{first} [{last}] is a code' print(message)
常见的内置函数
四舍五入 round()
x=2.9 print(round(x))
绝对值函数 abs
x=-2.9 print(abs(x))
调用math库
ceil向上取整
floor向下取整
import math print(math.ceil(2.9)) print(math.floor(2.9))
多层嵌套的结构,if:,elif:,else
is_hot=False is_cold=False if is_hot: print("it is a hot day") print("drink water") elif is_cold : print("it is a cold day") print("wear warm clothes") else: print("it is a warm day") print("enjoy your day") #跳出if条件
房价出售问题
credit=False price=1000000 if credit: price*=1.1 else: price*=1.2 print("you need to pay "+str(price)+" dollars") print(f"you need to pay:{price} dollars") #另一种输出形式
f字符是为了改进string.format(),即格式化字符串文字,常常与{}联用,格式{}里面的内容
逻辑运算
& 与 and
|| 或 or
! 非 not
income=True credit=True if income | credit : print("that is good")
比较运算符
,>=,>, <,<=
赋值运算 == !=
名字长度检测
a=input("your name \n") if(len(a)<3): print("name must be least 3 characters") elif (len(a)>10): print("name can be a maximum of 10 characters") else: print("name is ok")
体重评判程序
weight=input("Weight:") stand=input("(L)bs or (K)g:") if(stand.upper()=="L"): weight=float(weight)*2.0 print(f"you are {weight} pounds") elif (stand.upper()=="K"): weight=float(weight) print(f"you are {weight} kilogrammer") else: print("input must be choosen between 'L' or 'K'")
循环结构
i=1 while i<=5: print('*'*i) i+=1 print("done")
credit_num=9 try_num=0 while(try_num<=2): a=int(input("guess:")) if(a==9): print("you win!") break else: print("guess wrong,try again") try_num+=1 if(try_num>2): print("you have used three chioce") else: print("congraluation") # 猜数游戏 credit_num=9 try_num=0 while(try_num<=2): a=int(input("guess:")) if(a==9): print("you win!") break else: print("guess wrong,try again") try_num+=1 else: print("you have used three chioce") # 猜数游戏 简化运算
#简单的游戏 i=1 while i: a = input(">") if(a.lower()=='help'): print('start -to start the car') print('stop -to stop the car') print('quit to exit') elif (a.lower()=='start'): print('car started, ready to go') elif (a.lower()=='stop'): print('car stopped') elif(a.lower()=='quit'): break else: print("i don't understand that ....") i=1 while i: a = input(">") if(a.lower()=='help'): print('''start -to start the car stop -to stop the car quit to exit ''') elif (a.lower()=='start'): print('car started, ready to go') elif (a.lower()=='stop'): print('car stopped') elif(a.lower()=='quit'): break else: print("i don't understand that ....")
对于print 输出的状态,如果打三引号,可以直接输出无序换行
for循环
for item in 'python': print(item)
逐次打印python中每一个字母
for item in ['mosh','john','sarah']: print(item)
range()函数,在rang的范围内顺序产生在该范围内的数,其产生的是一个对象,不断的进行迭代
for item in range(20): print(item)
rang(a,b,c) a代表起始位置,b代表终点,c代表步长,左算右不算
for item in range(10,20,2): print(item
for循环实现成本
price=[10,20,30] total=0 for item in price: total=total+item print(f"total price is {total}")
嵌套循环
循环套循环
for x in range(5): for y in range(3): print(f"({x},{y})") 生成点坐标
numbers=[5,2,5,2,2] for x in numbers: print('x'*x) numbers=[5,2,5,2,2] for x in numbers: num='' for y in range(x): num+='x' print(num)
列表
最大值 num=[1,2,3,6,5,9] t=0 for i in num: if(i>t): t=i; print(t)
二维列表
# 二位列表 matrix=[ [1,2,3], [4,5,6], [7,8,9] ] for row in matrix: for item in row: print(item) # print(matrix[0][1])
列表函数操作
numbers=[2,2,4,3,5,6,5,2] unique=[] for number in numbers: if number not in unique: unique.append(number) unique.sort() print(unique) # # list=[1,2,3,5,4,5] # # list2=list.copy() # # list.remove(5) # # print(list) #
python解压缩特性
coordinates=(1,2,3) x,y,z,=coordinates print(y)
不仅可以在元组中应用,也可以在列表中使用
字典
每一个key在字典中都是唯一的
customer={ "name":'john', "sex":'man', "age": 40, "is_verified": True, } print(customer["is_verified"]) print(customer.get("name")) print(customer.get("birthday","Jan 1 1993"))
电话号码翻译
num={ '1':'one', '2':'two', '3':'three', '4':'four' } tele=input("phone:") output="" for i in tele: output+=num.get(i,"!") output+=' ' # if i in num: # print(num.get(i)) print(output)
message=input(">") words=message.split(' ') emojis={ ":)":"😀", ":(":"😭" } output="" for item in words: if not item in emojis: output+=item+' ' else: output+=emojis.get(item) #output += emojis.get(item,item) print(output)
函数
def greet_user(): print("hello") print('''i am a function, of course, i will company with you''') print('start') greet_user() print("finish")
传递信息到函数
def greet_user(name): print(f"hello {name}") print('''i am a function, of course, i will company with you''') print('start') greet_user("john") print("finish")
关键位置参数
def greet_user(name,last): print(f"hello {name} {last}") print('''i am a function, of course, i will company with you''') print('start') greet_user(last="smith",name="john") print("finish")
函数返回
return
函数实现表情识别
def emojis_recogize(string): emojis = { ":)": "😀", ":(": "😭" } words=string.split(' ') output = " " for item in words: output += emojis.get(item, item)+" " return output message=input(">") output=emojis_recogize(message) print(output)
错误异常
exit code 0 代表程序成功成功,没有错误
exit code 1 代表程序运行失败
try: age= int(input('age:')) print(age) except ValueError: print('InValid value')
try: age= int(input('age:')) income=20000 risk=income/age print(age) except ZeroDivisionError: print('age cannot to be 0 ') except ValueError: print('InValid value')
注释
类
class Point: def move(self): print("move") def draw(self): print("draw") poit1=Point() poit1.draw()
constructor
class Point: def __init__(self,x,y):#构造函数,初始化 self.x=x self.y=y def move(self): print("move") def draw(self): print("draw") poit1=Point(10,20) print(poit1.x)
class Person: def __init__(self,name): self.name=name def talk(self): print(f'{self.name} is talking') person1=Person("jack") person1.talk()
继承
class 子类(父类):子类继承父类
class Mammal: def walk(self): print("walk") class Dog(Mammal): def bark(self): print("bark") class Cat(Mammal): def be_annoying(self): print("annoying") dog1=Dog() dog1.walk() dog1.bark() cat1=Cat() cat1.be_annoying()
模块
def lbs_to_kg(weight): return weight*0.45 def kg_to_lbs(weight): return weight/0.45
import first #导入整个模块的代码 from first import kg_to_lbs #导入模块里的一个函数 print(first.kg_to_lbs(70)) print(kg_to_lbs(50))
模块化,取最大值
def find_max(list): t=list[0] for i in list: if(i>t): t=i; return t
import first #导入整个模块的代码 a=input("numberlist:") x=list(a)#字符串转列表 print(first.find_max(x))
包
def calc_shipping(): print("calc_shipping")
import ecommerce.shipping ecommerce.shipping.calc_shipping()
from ecommerce.shipping import calc_shipping calc_shipping()
import random members=['john','seven','mary','mosh'] leader=random.choice(members) print(leader)
随机数
import random class Dice: def roll(self): first= random.randint(1,6) second = random.randint(1, 6) return (first,second) num=Dice() print(num.roll())
import random class Dice: def roll(self): return random.randint(1,6) num=Dice() num2=Dice() yuanzu=(num.roll(),num2.roll()) print(yuanzu)
文件处理
绝对路径:电脑最开始的路径
相对路径:当前工作状态下的路径
from pathlib import Path path=Path("ecommerce") print(path.exists())
检测路径是否存在
显示当前路径下的所有文件
from pathlib import Path path=Path() for file in path.glob('*.*'): print(file)
对excel进行操作
import openpyxl as xl wb=xl.load_workbook('transaction.xlsx') sheet=wb['Sheet1'] cell=sheet['a1'] cell=sheet.cell(1,1) print(cell.value)
print(sheet.max_row) #打印出一页中最大有几行 for row in range(1,sheet.max_row +1): print(row) #遍历栏数 print(sheet.cell(row,3).value) for row in range(2,sheet.max_row +1): cell=sheet.cell(row, 3) correct=cell.value*0.9 correct_price=sheet.cell(row,4) correct_price.value=correct print(sheet.cell(row,4).value) wb.save('transaction2.xlsx') values=Reference(sheet, min_row=2, max_row=sheet.max_row, min_col=4, max_col=4) chart=BarChart() chart.add_data(values) sheet.add_chart(chart,'e2') wb.save('transaction2.xlsx')
模块化
import openpyxl as xl from openpyxl.chart import BarChart, Reference def process_workbook(filename): wb=xl.load_workbook(filename) sheet=wb['Sheet1'] for row in range(2,sheet.max_row +1): cell=sheet.cell(row, 3) correct=cell.value*0.9 correct_price=sheet.cell(row,4) correct_price.value=correct print(sheet.cell(row,4).value) values=Reference(sheet, min_row=2, max_row=sheet.max_row, min_col=4, max_col=4) chart=BarChart() chart.add_data(values) sheet.add_chart(chart,'e2') wb.save(filename)
机器学习
导入数据
清理重复数据
划分 训练模型 和 测试模型
创建模型
训练模型
做出预测
评估和提升
numpy 提供多维数组
pandas 数据分析库
matplotlib 二维绘图库
scikit_learn 提供算法库,决策树,神经网络
加载csv文件
import pandas as pd df=pd.read_csv('vgsales.csv') df.shape //数据大小 df.describe()//整体描述,各行各列 df.values//将表中的数据转化为二维数组
创建音乐推荐系统
创建输入输出
import pandas as pd music_data=pd.read_csv('music.csv') x=music_data.drop(columns='genre') y=music_data['genre']
选择算法(决策树)
from sklearn.tree import DecisionTreeClassifier #引入决策树算法 model=DecisionTreeClassifier() model.fit(x,y)#添入输入与输出 predictios=model.predict([[21,1],[22,0]])#模型预测,注意格式 predictios
测量准确性
import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split # 引入模块,使得数据分成训练与预测两方面 from sklearn.metrics import accuracy_score # 引入训练精度评判模块 music_data=pd.read_csv('music.csv') x=music_data.drop(columns=['genre']) y=music_data['genre'] x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2) # 0.8的数据做训练,0.2的数据做检验 model=DecisionTreeClassifier() model.fit(x_train,y_train) predictios=model.predict(x_test) score=accuracy_score(y_test,predictios) score
将模型储存,读取模型
import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split # 引入模块,使得数据分成训练与预测两方面 from sklearn.metrics import accuracy_score # 引入训练精度评判模块 from sklearn.externals import joblib #将训练好的模型保存 music_data=pd.read_csv('music.csv') x=music_data.drop(columns=['genre']) y=music_data['genre'] model=DecisionTreeClassifier() model.fit(x,y) joblib.dump(model,'music-recommender.joblib;') predictions=model.predict([[21,1]]) #使用模型 model=joblib.load('music-recommender.joblib;') predictions=model.predict([[21,1]]) predictions
决策树模型图像化
from sklearn import tree tree.export_graphviz(model, out_file='music-recommender.dot', feature_names=['age','gender'],#阶段分类规则 class_names=sorted(y.unique()),#类别名,排序 label='all',#把每个标签打印出来 rounded=True,#出现圆角 filled=True#代表生成的结点的颜色不同 )