title: python語(yǔ)法練習(xí)
參考阮一峰等多個(gè)文件用來(lái)練習(xí)python基本語(yǔ)法
[TOC]
import文件
參考文獻(xiàn)
- Python如何import文件夾下的文件: http://www.qttc.net/201209214.html
- http://codingpy.com/article/python-import-101/
常規(guī)導(dǎo)入
import sys import os, sys, time import sys as system #重命名 import urllib.error #某些子模塊必須要使用點(diǎn)標(biāo)記法才能導(dǎo)入。 如果兩個(gè)python文件位于同一文件夾下,可以直接通過(guò)import導(dǎo)入另一個(gè).py文件,并且使用其中的函數(shù)
使用from語(yǔ)句導(dǎo)入
很多時(shí)候你只想要導(dǎo)入一個(gè)模塊或庫(kù)中的某個(gè)部分:
from functools import lru_cache from os import path, walk, unlink #從一個(gè)包中導(dǎo)入多項(xiàng)
相對(duì)導(dǎo)入
可選導(dǎo)入
本地導(dǎo)入
if name == "main": 作用
參考文獻(xiàn)
上代碼
# Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
if __name__ == '__main__'
我們簡(jiǎn)單的理解就是: 如果模塊是被直接運(yùn)行的,則代碼塊被運(yùn)行,如果模塊是被導(dǎo)入的,則代碼塊不被運(yùn)行。over
python格式化輸出
打印
print ("和 is name is %s"%("gaolong")) #整數(shù) print ("He is %d years old"%(25)) #字符串 print ("His height is %f m"%(1.83))
?
over
python多線程
參考文獻(xiàn)
- Python2或者之前的多線程的模式:http://blog.csdn.net/jeanphorn/article/details/45195339
- 本人使用
python3.6.1
因此參考這篇文檔:http://www.cnblogs.com/fnng/p/3670789.html- ?
多線程的使用
def move(func): for i in range(5): print ("I was at the %s! %s" %(func, ctime())) def move(func): for i in range(2): print ("I was at the %s ! %s" %(func, ctime())) sleep(4) threads = [] t1 = threading.Thread(target=music, args=(u'aiqingmaima')) threads.append(t1) t2 = threading.Thread(target=move,args=(u'阿凡達(dá)',)) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() print ("all over %s" %ctime())
over
python魔術(shù)方法
python global
使用方法
a = 5 def test(): global a #此處聲明,告訴執(zhí)行引擎:我要用全局變量a,不要整成局部的了! a = 1 print 'In test func: a = %d' % a test() print 'Global a = %d' % a 首先:python使用的變量,在默認(rèn)情況下一定是用局部變量。 其次:python如果想使用作用域之外的全局變量,則需要加global前綴。
over
requests框架學(xué)習(xí)
這個(gè)框架的作用類似于iOS的post請(qǐng)求、get請(qǐng)求,即url請(qǐng)求,獲取數(shù)據(jù)。數(shù)據(jù)類型可能是json,可能是html網(wǎng)頁(yè)。
參考文獻(xiàn)
requests基本用法: https://zhuanlan.zhihu.com/p/26681429
基本用法
使用pycharm+virtualenv, 導(dǎo)入requests框架。requests抓取網(wǎng)頁(yè)。
#made by schiller import requests payload = dict(catCircleCategoryId=2, sortType=1) r = requests.post("http://app.yirimao.com/cat-circle/list", data=payload) # print(r.text) def getHtmlText(url): try: r = requests.get(url, timeout=30) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return "Something wrong!"
if name == 'main':
print(getHtmlText("http://www.aidu.com"))3. **kwargs參數(shù) 4. 兩個(gè)常用控制訪問(wèn)的參數(shù) - 假設(shè)我們需要在GET請(qǐng)求里自定義一個(gè)header頭文件: ```python import requests hd = {'User-agent':'123'} r = requests.get('http://www.baidu.com', headers=hd) print(r.request.headers) ''' OUT: {'User-agent': '123', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive '} '''
假設(shè)我們要自定義一個(gè)代理池
pxs = { 'http': 'http://user:pass@10.10.10.1:1234', 'https': 'https://10.10.10.1:4321' } r = requests.get('http://www.baidu.com', proxies=pxs)
over
詳解response對(duì)象
import requests r = requests.get("http://www.baidu.com") ''' Response(self) The :class:Response <Response> object, which contains a server's response to an HTTP request. ''' #HTTP請(qǐng)求的返回狀態(tài),比如,200表示成功,404表示失敗 print (r.status_code) #HTTP請(qǐng)求中的headers print (r.headers) #從header中猜測(cè)的響應(yīng)的內(nèi)容編碼方式 print (r.encoding) #從內(nèi)容中分析的編碼方式(慢) print (r.apparent_encoding) #響應(yīng)內(nèi)容的二進(jìn)制形式 print (r.content) ''' status_code:200 headers: {'Server': 'bfe/1.0.8.18', 'Date': 'Tue, 02 May 2017 12:01:47 GMT', 'Content-Type': 'text/html', 'La st-Modified': 'Mon, 23 Jan 2017 13:28:27 GMT', 'Transfer-Encoding': 'chunked', 'Connection': 'Keep-A live', 'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Pragma': 'no -cache', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Content-Encoding': 'gzip'} encoding: ISO-8859-1 apparent_encoding:utf-8 '''
over
beautifulsoup4 html 解析器
beautifulsoup4是一個(gè)強(qiáng)大的html解析器
參考文獻(xiàn)
基本用法
from bs4 import BeautifulSoup import myrequest html = myrequest.getHtmlText('http://www.baidu.com') soup = BeautifulSoup(html, 'html.parser') print(soup.prettify()) def getSoupValue(): title = soup.title name = soup.title.name titleString = soup.title.string titleParentString = soup.title.parent.name ptag = soup.p aAll = soup.find_all('a') print("title = %s, name = %s, titlestring = %s,titlePrentstring = %s, ptag = %s, a = %s" % (title, name, titleString, titleParentString, ptag, aAll))
if name == 'main':
getSoupValue()3. bs4庫(kù) 是解析、遍歷、維護(hù)、“標(biāo)簽樹“的功能庫(kù)。 4. over
bs4解析器 lxml
網(wǎng)絡(luò)爬蟲的最終目的就是過(guò)濾選取網(wǎng)絡(luò)信息,最重要的部分可以說(shuō)是解析器。解析器的優(yōu)劣決定了爬蟲的速度和效率。bs4庫(kù)除了支持我們上文用過(guò)的‘html.parser’解析器外,還支持很多第三方的解析器,下面我們來(lái)對(duì)他們進(jìn)行對(duì)比分析。
參考文獻(xiàn)
基本用法
import bs4 html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a class="sister" id="link1">Elsie</a>, <a class="sister" id="link2">Lacie</a> and <a class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ #soup = bs4.BeautifulSoup(open(''), 'lxml') soup = bs4.BeautifulSoup(html_doc, 'lxml') print(soup.prettify()) def dealWithTags(): head = soup.head title = soup.title body = soup.body.b tag = soup.find_all('a') nee = tag[1]
over
爬蟲實(shí)踐:獲取百度貼吧內(nèi)容
over
python經(jīng)典編碼問(wèn)題
python scrapy爬蟲框架入門
參考文獻(xiàn):
- 使用virtaulenv和pycharm導(dǎo)入Scrapy
- 使用簡(jiǎn)書案例,新建jianshuSpider.py文件
- 配置setting.py
- 新建main.py用來(lái)執(zhí)行python腳本
- 也可以通過(guò)virtaulenv的命令,cd到簡(jiǎn)書項(xiàng)目中,執(zhí)行scrapy startproject jianshu 腳本來(lái)執(zhí)行該項(xiàng)目
- over
爬取簡(jiǎn)書文檔數(shù)據(jù)
參考文獻(xiàn):http://www.lxweimin.com/p/61911e00abd0
over
使用scrapy框架爬取天氣資訊
參考文獻(xiàn):https://zhuanlan.zhihu.com/p/26885412
步驟:
安裝scrapy
直接通過(guò)pycharm 導(dǎo)入該框架即可
生成 uuu scrapy項(xiàng)目
$ cd .virtualenvs/py3env_test #進(jìn)入該虛擬目錄 $ source bin/activate # 激活env $ cd $ cd python_test (py3env_test) ? python_test git:(master) ? scrapy startproject spiderDemo # 使用scrapy快速建立新項(xiàng)目,使用的是py3env_test虛擬目錄的python框架 $ cd spiderDemo $ 再進(jìn)入pycharm就能看到自己新建的scrapy項(xiàng)目了。
編寫items.py
import scrapy
class WeatherItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
date = scrapy.Field()
week = scrapy.Field()
img = scrapy.Field()
temperature = scrapy.Field()
weather = scrapy.Field()
wind = scrapy.Field()4. 編寫spider ```python 在spiders目錄下新建:SZtianqi.py文件 # -*- coding: utf-8 -*- import scrapy from weather.items import WeatherItem class SztianqiSpider(scrapy.Spider): name = "SZtianqi" # 我們修改一下host,使得Scrapy可以爬取除了蘇州之外的天氣 allowed_domains = ["tianqi.com"] # 建立需要爬取信息的url列表 start_urls = [] # 需要爬的城市名稱 citys = ['nanjing', 'suzhou', 'shanghai'] # 用一個(gè)很簡(jiǎn)答的循環(huán)來(lái)生成需要爬的鏈接: for city in citys: start_urls.append('http://' + city + '.tianqi.com') def parse(self, response): ''' 篩選信息的函數(shù): date = 今日日期 week = 星期幾 img = 表示天氣的圖標(biāo) temperature = 當(dāng)天的溫度 weather = 當(dāng)天的天氣 wind = 當(dāng)天的風(fēng)向 ''' # 先建立一個(gè)列表,用來(lái)保存每天的信息 items = [] # 找到包裹著每天天氣信息的div sixday = response.xpath('//div[@class="tqshow1"]') # 循環(huán)篩選出每天的信息: for day in sixday: # 先申請(qǐng)一個(gè)weatheritem 的類型來(lái)保存結(jié)果 item = WeatherItem() # 觀察網(wǎng)頁(yè),知道h3標(biāo)簽下的不單單是一行str,我們用trick的方式將它連接起來(lái) date = '' for datetitle in day.xpath('./h3//text()').extract(): date += datetitle item['date'] = date item['week'] = day.xpath('./p//text()').extract()[0] item['img'] = day.xpath( './ul/li[@class="tqpng"]/img/@src').extract()[0] tq = day.xpath('./ul/li[2]//text()').extract() # 我們用第二種取巧的方式,將tq里找到的str連接 item['temperature'] = ''.join(tq) item['weather'] = day.xpath('./ul/li[3]/text()').extract()[0] item['wind'] = day.xpath('./ul/li[4]/text()').extract()[0] items.append(item) return items
編寫pipelines
pipelines.py是用來(lái)處理收尾爬蟲抓到的數(shù)據(jù)的,一般情況下,我們會(huì)將數(shù)據(jù)存到本地: 1、文本形式:最基本 2、json格式:方便調(diào)用 3、數(shù)據(jù)庫(kù):數(shù)據(jù)量大 此處使用json格式 class W2json(object): def process_item(self, item, spider): ''' 講爬取的信息保存到j(luò)son 方便其他程序員調(diào)用 ''' base_dir = os.getcwd() filename = base_dir + '/data/weather.json' # 打開json文件,向里面以dumps的方式吸入數(shù)據(jù) # 注意需要有一個(gè)參數(shù)ensure_ascii=False ,不然數(shù)據(jù)會(huì)直接為utf編碼的方式存入比如:“/xe15” with codecs.open(filename, 'a') as f: line = json.dumps(dict(item), ensure_ascii=False) + '\n' f.write(line) return item
編寫settings.py
我們需要在Settings.py將我們寫好的PIPELINE添加進(jìn)去,
scrapy才能夠跑起來(lái)
這里只需要增加一個(gè)dict格式的ITEM_PIPELINES,
數(shù)字value可以自定義,數(shù)字越小的優(yōu)先處理BOT_NAME = 'weather' SPIDER_MODULES = ['weather.spiders'] NEWSPIDER_MODULE = 'weather.spiders' ITEM_PIPELINES = {'weather.pipelines.W2json': 400} ROBOTSTXT_OBEY = True
讓項(xiàng)目跑起來(lái)
$ cd weather 項(xiàng)目目錄 $ 在weather目錄下新建一個(gè) data/weather.json文件用來(lái)收錄抓取的數(shù)據(jù) $ scrapy crawl SZtianqi
over
over
需要解決的問(wèn)題
- virtaulenv 使用pip列出virtaulenv安裝過(guò)的第三方庫(kù)
- python爬蟲框架scrapy
- python爬取有關(guān)于貓的一切資料
- ?
python序列化
python序列化,將字典轉(zhuǎn)成json或者將json轉(zhuǎn)成字典
案
import hashlib import json md5 = hashlib.md5() md5.update('how to use md5 in python'.encode('utf-8')) print(md5.hexdigest()) d = dict(name='Bob', age=20,score=90) print(json.dumps(d)) #此處是dumps而不是dump json_str = '{"name": "Bob", "age": 20, "score": 90, "result":true}' print(json.loads(json_str)) adict = json.loads(json_str) print(adict) #定義類 class Student(object): def __init__(self, name, age, score): self.name = name self.age = age self.score = score def student2dict(std): return { 'name': std.name, 'age': std.age, 'score': std.score } a = Student('Bob', 20, 88) print(json.dumps(a, default=student2dict)) #將對(duì)象轉(zhuǎn)成json print(json.dumps(a, default=lambda obj: obj.__dict__)) #將任意對(duì)象轉(zhuǎn)成json,定義一個(gè)匿名函數(shù)
over
over
高階函數(shù)
map、reduce、filter、sorted
python Django入門
采用virtualenv引入django。
參考文檔:https://www.lijinlong.cc/django/djxs/1920.html
自學(xué)入門:https://code.ziqiangxuetang.com/django/django-intro.html
打開pycharm,打開工程tieba,本工程采用的env是virtualenv。來(lái)自 ~/.virtualenvs/ py3env_test
可以用Pycharm/Preferences/ 去下載最新的django。我下載的是2.1版本。下載好的django會(huì)存放到這個(gè)virtualenv的site-packages目錄下。
然后進(jìn)入到py3env_test , 運(yùn)行source bin/activate,激活這個(gè)虛擬環(huán)境
ok,激活后,執(zhí)行pip3 install django。由于我用pycharm導(dǎo)入的這個(gè)框架,所以此處提醒我已經(jīng)安裝好了。
使用命令創(chuàng)建項(xiàng)目:django-admin.py startproject
myfirstDjangoProject
。這個(gè)項(xiàng)目最后會(huì)存放到 ~/ 目錄下。可以指定創(chuàng)建目錄到python_test
cd 到 工程 myfirstDjangoProject,然后執(zhí)行 python manage.py runserver
打開瀏覽器:
Django version 2.0.1, using settings 'myfirstDjangoProject.settings' Starting development server at http://127.0.0.1:8000/
創(chuàng)建mydjango_app ,并且,創(chuàng)建views.py, 創(chuàng)建第一個(gè)django應(yīng)用。
總結(jié)一句:第一步,打開虛擬環(huán)境;第二步,創(chuàng)建項(xiàng)目(如果已經(jīng)有項(xiàng)目則cd到項(xiàng)目) ;第三步,到工程里運(yùn)行項(xiàng)目
去掉提示 migration提醒
#Django 1.7.x 以下版本 python manage.py syncdb # Django 1.7.x 以及上要用 python manage.py migrate
?
over
Django視圖與網(wǎng)址以及進(jìn)階
參考文檔:https://code.ziqiangxuetang.com/django/django-views-urls.html
參考文檔2:https://code.ziqiangxuetang.com/django/django-views-urls2.html
新建一個(gè)APP,名稱為learn
python manage.py startapp learn ``# learn 是一個(gè)app的名稱
把我們新定義的app加到settings.py中的****INSTALL_APPS中
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learn', )
我們?cè)趌earn這個(gè)目錄中,把views.py打開,修改其中的源代碼,改成下面的
# coding:utf-8 from django.http import HttpResponse def index(request): return HttpResponse(u"歡迎光臨 自強(qiáng)學(xué)堂!")
定義視圖函數(shù)相關(guān)的url
from django.conf.urls import url from django.contrib import admin from learn import views as learn_views # new urlpatterns = [ url(r'^$', learn_views.index), # new url(r'^admin/', admin.site.urls), ]
修改視圖views.py文件為
from django.shortcuts import render from django.http import HttpResponse def add(request): a = request.GET['a'] b = request.GET['b'] c = int(a)+int(b) return HttpResponse(str(c))
修改為
from django.conf.urls import url from django.contrib import admin from calc import views as calc_views urlpatterns = [ url(r'^add/$', calc_views.add, name='add'), # 注意修改了這一行 url(r'^admin/', admin.site.urls), ]
打開網(wǎng)址:http://127.0.0.1:8000/add/
已經(jīng)學(xué)到QuerySet API 這一章節(jié)
python細(xì)微語(yǔ)法總結(jié)
函數(shù)
1. 函數(shù)、參數(shù)、高階函數(shù)、None 位置參數(shù) def add_end(L=None): if L is None: L = [] L.append('END') return L 可變參數(shù) def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum 關(guān)鍵字參數(shù) **args 可變參數(shù)允許你傳入0個(gè)或任意個(gè)參數(shù),這些可變參數(shù)在函數(shù)調(diào)用時(shí)自動(dòng)組裝為一個(gè)tuple。而關(guān)鍵字參數(shù)允許你傳入0個(gè)或任意個(gè)含參數(shù)名的參數(shù),這些關(guān)鍵字參數(shù)在函數(shù)內(nèi)部自動(dòng)組裝為一個(gè)dict 命名關(guān)鍵字參數(shù),如果要限制關(guān)鍵字參數(shù)的名字,就可以用命名關(guān)鍵字參數(shù)。用*分隔符 分割 如果函數(shù)定義中已經(jīng)有了一個(gè)可變參數(shù),后面跟著的命名關(guān)鍵字參數(shù)就不再需要一個(gè)特殊分隔符*了 命名關(guān)鍵字參數(shù)必須傳入?yún)?shù)名,這和位置參數(shù)不同 //總結(jié) 必選參數(shù)、默認(rèn)參數(shù)、位置參數(shù)、可變參數(shù)、關(guān)鍵字參數(shù)、命名關(guān)鍵字參數(shù)、參數(shù)組合 參數(shù)定義的順序必須是:必選參數(shù)、默認(rèn)參數(shù)、可變參數(shù)、命名關(guān)鍵字參數(shù)和關(guān)鍵字參數(shù)。 2. list、tuple 3. 高級(jí)特性 切片 L = list(range(100)) L[0:3] 同L[:3] L[1:3] L[-2:] L[:10:2] 前10個(gè)數(shù),每?jī)蓚€(gè)取一個(gè):[0, 2, 4, 6, 8] 'ABCDEFG'[::2] 迭代 列表生成式 生成器 迭代器 4. 函數(shù)式編程 map reduce filter sorted 返回函數(shù) 匿名函數(shù): list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) 裝飾器 def now(): ... print('2015-3-25') 假設(shè)我們要增強(qiáng)now()函數(shù)的功能,比如,在函數(shù)調(diào)用前后自動(dòng)打印日志,但又不希望修改now()函數(shù)的定義,這種在代碼運(yùn)行期間動(dòng)態(tài)增加功能的方式,稱之為“裝飾器”(Decorator)。 #裝飾器 def log(func): def wrapper(*arg, **kw): print('call %s():' % func.__name__) return func(*arg, **kw) return wrapper @log def now(): print('2018-4-26') now() 偏函數(shù)
模塊
1. 使用模塊 任何模塊代碼的第一個(gè)字符串都被視為模塊的文檔注釋 __author__ = 'Michael Liao' 2. 運(yùn)行 if __name__=='__main__': test() 當(dāng)我們?cè)诿钚羞\(yùn)行hello模塊文件時(shí),Python解釋器把一個(gè)特殊變量__name__置為__main__,而如果在其他地方導(dǎo)入該hello模塊時(shí),if判斷將失敗。 3. 作用域 public:正常的函數(shù)和變量名是公開的(public),可以被直接引用,比如:abc,x123,PI等 __xxx__這樣的變量是特殊變量,可以被直接引用,但是有特殊用途,比如上面的__author__,__name__就是特殊變量 類似_xxx和__xxx這樣的函數(shù)或變量就是非公開的(private),不應(yīng)該被直接引用,比如_abc,__abc等
面向?qū)ο?/p>
1. __init__方法的第一個(gè)參數(shù)永遠(yuǎn)是self,表示創(chuàng)建的實(shí)例本身,因此,在__init__方法內(nèi)部,就可以把各種屬性綁定到self,因?yàn)閟elf就指向創(chuàng)建的實(shí)例本身 2.類: 要定義一個(gè)方法,除了第一個(gè)參數(shù)是self外,其他和普通函數(shù)一樣。 3. 訪問(wèn)限制 4. 繼承+多態(tài) 5. 獲取對(duì)象信息 type() isinstance() 6. __slots__ Python允許在定義class的時(shí)候,定義一個(gè)特殊的__slots__變量,來(lái)限制該class實(shí)例能添加的屬性 class Student(object): __slots__ = ('name', 'age') # 用tuple定義允許綁定的屬性名稱 7. 使用@property class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value 8. 多重繼承、枚舉類
正則表達(dá)式
\d
可以匹配一個(gè)數(shù)字,\w
可以匹配一個(gè)字母或數(shù)字,\s匹配空格
.
可以匹配任意字符用
*
表示任意個(gè)字符(包括0個(gè)),用+
表示至少一個(gè)字符,用?
表示0個(gè)或1個(gè)字符,用{n}
表示n個(gè)字符,用{n,m}
表示n-m個(gè)字符
'-'
是特殊字符,在正則表達(dá)式中,要用'\'
轉(zhuǎn)義要做更精確地匹配,可以用
[]
表示范圍
[0-9a-zA-Z\_]
可以匹配一個(gè)數(shù)字、字母或者下劃線
A|B
可以匹配A或B
^
表示行的開頭,^\d
表示必須以數(shù)字開頭。
$
表示行的結(jié)束,\d$
表示必須以數(shù)字結(jié)束re模塊
強(qiáng)烈建議使用Python的
r
前綴,就不用考慮轉(zhuǎn)義的問(wèn)題了def matchResult(test): if re.match(r'^\d{3}\-\d{3,8}$', test): print('ok,hhh,match ok') else: print('failed') matchResult('010-12345') 分組: 貪婪匹配: 編譯:
over
python常用內(nèi)建模塊
datetime & collections & base64 & struct & hashlib & hmac & zip
zip() 函數(shù)用于將可迭代的對(duì)象作為參數(shù),將對(duì)象中對(duì)應(yīng)的元素打包成一個(gè)個(gè)元組,然后返回由這些元組組成的列表 >>>a = [1,2,3] >>> b = [4,5,6] >>> zipped = zip(a,b) [(1, 4), (2, 5), (3, 6)]
itertools & contextlib & contextlib & urllib & XML & HTMLParser
argparse
該模塊用于解析通過(guò)命令行運(yùn)行的參數(shù) $ python a.py 10 20 解析10 20這些基本參數(shù) 該模塊有基本用法, import argparse parser = argparse.ArgumentParser() parser.add_argument('--batch_size', default=100, type=int, help='batch size') #然后 args = parser.parse_args()
python內(nèi)置函數(shù):http://www.runoob.com/python/python-built-in-functions.html
over
模塊
連接數(shù)據(jù)庫(kù)
#MySQL官方提供了mysql-connector-python驅(qū)動(dòng),但是安裝的時(shí)候需要給pip命令加上參數(shù)--allow-external import mysql.connector def connectMysql(): conn = mysql.connector.connect(user='root', password='gaolong', database='yirimao_2018_4') cursor = conn.cursor() sql = 'select * from user where id = 144' cursor.execute(sql) print(cursor.fetchall()) connectMysql()
異步IO
?
over
pandas庫(kù)學(xué)習(xí)
參考文獻(xiàn):http://codingpy.com/article/a-quick-intro-to-pandas/
import pandas as pd def load_data(y_name='Species'): CSV_COLUMN = ['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth', 'Species'] path = '/Users/gl/Desktop/iris_training.csv' train = pd.read_csv(path, names=CSV_COLUMN, header=0) #pop刪除某列,返回刪除的那一列的數(shù)據(jù),此處為簡(jiǎn)單賦值 train_x, train_y = train, train.pop(y_name) return (train_x, train_y) print(load_data()) 接口: df.tail() df.head() df['rain_octsep']或者df.rain_octsep 布爾過(guò)濾:df.rain_octsep < 1000 索引:df.iloc[30] 對(duì)數(shù)據(jù)集應(yīng)用函數(shù): def base_year(year): base_year = year[:4] base_year= pd.to_datetime(base_year).year return base_year df['year'] = df.water_year.apply(base_year) df.head(5) 數(shù)據(jù)集結(jié)構(gòu)操作 合并數(shù)據(jù)集: 使用Pandas快速作圖:
ove
Numpy快速入門
參考文獻(xiàn):http://codingpy.com/article/an-introduction-to-numpy/
Python 學(xué)習(xí)數(shù)據(jù)科學(xué)或者機(jī)器學(xué)習(xí),就必須學(xué)習(xí) NumPy
1. 創(chuàng)建二位數(shù)組、矩陣 2. 多維數(shù)組切片 3. 數(shù)組屬性 4.
over
TensorFlow入門
機(jī)器學(xué)習(xí)新手入門:https://www.tensorflow.org/get_started/get_started_for_beginners
模型與訓(xùn)練
模型即特征與標(biāo)簽之間的關(guān)系。對(duì)于鳶尾花問(wèn)題,模型定義了花萼和花瓣測(cè)量值與鳶尾花品種之間的關(guān)系。一些簡(jiǎn)單的模型可以用幾行代數(shù)進(jìn)行描述;比較復(fù)雜的機(jī)器學(xué)習(xí)模型則包含大量的交錯(cuò)數(shù)學(xué)函數(shù)和參數(shù),以至于難以從數(shù)學(xué)角度進(jìn)行總結(jié) 監(jiān)督式學(xué)習(xí) 非監(jiān)督式學(xué)習(xí)
獲取示例程序
1. 安裝TensorFlow(使用virtualenv直接導(dǎo)入該pachkage) 2. 安裝Pandas庫(kù) 3. 獲取代碼:git clone https://github.com/tensorflow/models 4. cd models/samples/core/get_started/ 5. python premade_estimator.py
高階API:
Estimator
和Dataset
程序流程
1. 導(dǎo)入和解析數(shù)據(jù)集。 2. 創(chuàng)建特征列以描述數(shù)據(jù)。 3. 選擇模型類型。 4. 訓(xùn)練模型。 5. 評(píng)估模型的效果。 6. 讓經(jīng)過(guò)訓(xùn)練的模型進(jìn)行預(yù)測(cè)。
?
over