笔记
函数三种定义方式
- 无参函数,不需要接受外部传入的参数
def foo():
print('from foo)
foo()
- 有参函数,需要接受外部传入参数
def login(user,pwd):
print(user,pwd)
login('tian','666')
- 空函数
def func():
pass
函数返回值
def max2(x,y):
if x > y:
return(x)
else:
return(y)
res = max2(2,3)
print('res =',res)
函数对象-函数名指向的的内存地址
def func():
pass
def func2():
pass
dict1 = {'1':func,'2':func2()}
choice = input('请输入功能编号:').strip()
if choice in dict1:
dict1[(choice)]()
嵌套函数
- 嵌套定义
在函数内定义函数
def func1():
print('func1..')
def func2():
print('func2..')
return func2
func2 = func1()
func2()
- 嵌套调用
def func1():
print('func1..')
def func2():
print('func2..')
func2()
func1()
函数名称空间
name = 'tian' # 全局名称空间
def func1():
print(name)
def func2(): # 局部名称空间
print('func2..')
func1()
模块与包
import T
from T import t
t
- 模块里面测试
def func1():
print('xin')
if __name__ == '__main__':
func1()
内置模块
- time模块
# time
import time # 获取时间戳
print(time.time())
# 等待
time.sleep(2)
print(time.time())
- datetime模块
- random模块
- os模块
# 与操作系统中的文件进行交互
import os
# 判断xinxin.txt文件是否存在
print(os.path.exists('xinxin.txt'))
print(os.path.exists(r'D:\tianxinxinpython\xinxin.txt'))
# 获取当前根目录
print(os.path.dirname(__file__))
- sys模块
import sys
# 获取python在环境变量中的文件路径
print(sys.path)
# 把项目根目录添加到环境变量中
sys.path.append(os.path.dirname(__file__))
print(sys.path)
- json和pickle模块
dump:序列化
把字典转换成json数据
再把json数据转换成字符串
import json
user_info = {
'name' : 'tian',
'pwd' : '123'
}
res = json.dumps(user_info)
print(res)
print(type(res))
with open('user.json','wt',encoding='utf-8') as f:
f.write(res)
load:反序列化
json.load()
把json文件的数据读到内存中
ith open('user.json','r',encoding='utf-8') as f:
res = f.read()
user_dict = json.load(res)
print(user_dict)
print(type(user_dict))
dump自动触发f.write功能
user_info = {
'name':'tian',
'pwd':'123'
}
with open('user_info.json','w',encoding='utf-8') as f:
json.dump(user_info,f)
print(user_info)
load自动触发f.write功能
user_info = {
'name':'tian',
'pwd':'123'
}
with open('user.json','r',encoding='utf-8') as f:
# res = f.read()
# user_dict = json.load(res)
# print(user_dict)
user_dict = json.load(f)
print(user_dict)
- hashlib模块
- logging模块
- re模块
- numpy模块
- pandas模块
- matplotlib模块
爬虫基本原理
# requests模块的使用
# <对象>
import requests
response = requests.get(url='https://www.baidu.com/')
response.encoding = 'utf-8'
print(response) # <Response [200]>
# 返回响应状态码
print(response.status_code) # 200
# 返回响应文本
print(response.text)
print(type(response.text))
with open('baidu.html','w',encoding='utf-8') as f:
f.write(response.text)
# 爬视频
res = requests.get('https://video.pearvideo.com/mp4/adshort/20190613/cont-1565852-14013295_adpkg-ad_hd.mp4')
print(res.content)
with open('视频.mp4','wb') as f:
f.write(res.content)
作业
库里扣篮视频
res = requests.get('http://f.us.sinaimg.cn/0039hF2Slx07unNLa7Ak01041204zgwJ0E020.mp4?label=mp4_ld&template=640x360.20.0&Expires=1560436690&ssig=Ef%2B%2FBaTgel&KID=unistore,video')
print(res.content)
with open('stephen扣篮.mp4','wb') as f:
f.write(res.content)