python笔记
模块、包
在一个目录下建立一个helpers,py文件、
内容:
def display(massage,is_waring=False):
if is_waring:
print('this is waring')
print('massage')
同一文件下建立新文件:
#三种导入方式:(代码执行效率都一样)
import helpers
helpers.display('simpmassage',True)
from helpers import *
display('simpmassage',True)
from helpers import display
display('simpmassage',True)
虚拟实验环境
# 安装虚拟环境要用的包
pip install virtualenv
# 在一个文件夹内创建虚拟环境
python -m venv 虚拟环境名
# 激活虚拟环境
.\venv\Scripts\activate
# 在工作空间下安装新建一个txt文件来保存导入的包的名字
pip intsall myWorkPlace.txt
调用API
下面用百度API为例,调用实例(人脸识别):
注册百度云人工智能:百度AI开放平台
创建一个应用:
得到一个应用列表:记录API key和Secret Key
获取:
# encoding:utf-8
import requests
import json
AK='【你的API key】'
SK='【你的Secret Key】'
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+AK+'&client_secret='+SK
response = requests.get(host)
if response:
print(response.json())
else:
print('error')
在结果中查看 access_token
注意:access_token的有效期为30天,切记需要每30天进行定期更换,或者每次请求都拉取新token;
当前目录下建立image图片目录,具体参数参考百度AI文档
'''
人脸检测与属性分析
'''
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
params = "{\"image\":\"027d8308a2ec665acb1bdf63e513bcb9\",\"image_type\":\"FACE_TOKEN\",\"face_field\":\"faceshape,facetype\"}"
access_token = '【你的access_token】'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)
if response:
print (response.json())