title: python語法練習
參考阮一峰等多個文件用來練習python基本語法
[TOC]
import文件
參考文獻
- Python如何import文件夾下的文件: http://www.qttc.net/201209214.html
- http://codingpy.com/article/python-import-101/
常規導入
import sys import os, sys, time import sys as system #重命名 import urllib.error #某些子模塊必須要使用點標記法才能導入。 如果兩個python文件位于同一文件夾下,可以直接通過import導入另一個.py文件,并且使用其中的函數
使用from語句導入
很多時候你只想要導入一個模塊或庫中的某個部分:
from functools import lru_cache from os import path, walk, unlink #從一個包中導入多項
相對導入
可選導入
本地導入
if name == "main": 作用
參考文獻
上代碼
# 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__'
我們簡單的理解就是: 如果模塊是被直接運行的,則代碼塊被運行,如果模塊是被導入的,則代碼塊不被運行。over
python格式化輸出
打印
print ("和 is name is %s"%("gaolong")) #整數 print ("He is %d years old"%(25)) #字符串 print ("His height is %f m"%(1.83))
?
over
python多線程
參考文獻
- 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'阿凡達',)) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() print ("all over %s" %ctime())
over
python魔術方法
python global
使用方法
a = 5 def test(): global a #此處聲明,告訴執行引擎:我要用全局變量a,不要整成局部的了! a = 1 print 'In test func: a = %d' % a test() print 'Global a = %d' % a 首先:python使用的變量,在默認情況下一定是用局部變量。 其次:python如果想使用作用域之外的全局變量,則需要加global前綴。
over
requests框架學習
這個框架的作用類似于iOS的post請求、get請求,即url請求,獲取數據。數據類型可能是json,可能是html網頁。
參考文獻
requests基本用法: https://zhuanlan.zhihu.com/p/26681429
基本用法
使用pycharm+virtualenv, 導入requests框架。requests抓取網頁。
#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參數 4. 兩個常用控制訪問的參數 - 假設我們需要在GET請求里自定義一個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 '} '''
假設我們要自定義一個代理池
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對象
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請求的返回狀態,比如,200表示成功,404表示失敗 print (r.status_code) #HTTP請求中的headers print (r.headers) #從header中猜測的響應的內容編碼方式 print (r.encoding) #從內容中分析的編碼方式(慢) print (r.apparent_encoding) #響應內容的二進制形式 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是一個強大的html解析器
參考文獻
基本用法
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庫 是解析、遍歷、維護、“標簽樹“的功能庫。 4. over
bs4解析器 lxml
網絡爬蟲的最終目的就是過濾選取網絡信息,最重要的部分可以說是解析器。解析器的優劣決定了爬蟲的速度和效率。bs4庫除了支持我們上文用過的‘html.parser’解析器外,還支持很多第三方的解析器,下面我們來對他們進行對比分析。
參考文獻
基本用法
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
爬蟲實踐:獲取百度貼吧內容
over
python經典編碼問題
python scrapy爬蟲框架入門
參考文獻:
- 使用virtaulenv和pycharm導入Scrapy
- 使用簡書案例,新建jianshuSpider.py文件
- 配置setting.py
- 新建main.py用來執行python腳本
- 也可以通過virtaulenv的命令,cd到簡書項目中,執行scrapy startproject jianshu 腳本來執行該項目
- over
爬取簡書文檔數據
參考文獻:http://www.lxweimin.com/p/61911e00abd0
over
使用scrapy框架爬取天氣資訊
參考文獻:https://zhuanlan.zhihu.com/p/26885412
步驟:
安裝scrapy
直接通過pycharm 導入該框架即可
生成 uuu scrapy項目
$ cd .virtualenvs/py3env_test #進入該虛擬目錄 $ source bin/activate # 激活env $ cd $ cd python_test (py3env_test) ? python_test git:(master) ? scrapy startproject spiderDemo # 使用scrapy快速建立新項目,使用的是py3env_test虛擬目錄的python框架 $ cd spiderDemo $ 再進入pycharm就能看到自己新建的scrapy項目了。
編寫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'] # 用一個很簡答的循環來生成需要爬的鏈接: for city in citys: start_urls.append('http://' + city + '.tianqi.com') def parse(self, response): ''' 篩選信息的函數: date = 今日日期 week = 星期幾 img = 表示天氣的圖標 temperature = 當天的溫度 weather = 當天的天氣 wind = 當天的風向 ''' # 先建立一個列表,用來保存每天的信息 items = [] # 找到包裹著每天天氣信息的div sixday = response.xpath('//div[@class="tqshow1"]') # 循環篩選出每天的信息: for day in sixday: # 先申請一個weatheritem 的類型來保存結果 item = WeatherItem() # 觀察網頁,知道h3標簽下的不單單是一行str,我們用trick的方式將它連接起來 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是用來處理收尾爬蟲抓到的數據的,一般情況下,我們會將數據存到本地: 1、文本形式:最基本 2、json格式:方便調用 3、數據庫:數據量大 此處使用json格式 class W2json(object): def process_item(self, item, spider): ''' 講爬取的信息保存到json 方便其他程序員調用 ''' base_dir = os.getcwd() filename = base_dir + '/data/weather.json' # 打開json文件,向里面以dumps的方式吸入數據 # 注意需要有一個參數ensure_ascii=False ,不然數據會直接為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添加進去,
scrapy才能夠跑起來
這里只需要增加一個dict格式的ITEM_PIPELINES,
數字value可以自定義,數字越小的優先處理BOT_NAME = 'weather' SPIDER_MODULES = ['weather.spiders'] NEWSPIDER_MODULE = 'weather.spiders' ITEM_PIPELINES = {'weather.pipelines.W2json': 400} ROBOTSTXT_OBEY = True
讓項目跑起來
$ cd weather 項目目錄 $ 在weather目錄下新建一個 data/weather.json文件用來收錄抓取的數據 $ scrapy crawl SZtianqi
over
over
需要解決的問題
- virtaulenv 使用pip列出virtaulenv安裝過的第三方庫
- python爬蟲框架scrapy
- python爬取有關于貓的一切資料
- ?
python序列化
python序列化,將字典轉成json或者將json轉成字典
案
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)) #將對象轉成json print(json.dumps(a, default=lambda obj: obj.__dict__)) #將任意對象轉成json,定義一個匿名函數
over
over
高階函數
map、reduce、filter、sorted
python Django入門
采用virtualenv引入django。
參考文檔:https://www.lijinlong.cc/django/djxs/1920.html
自學入門:https://code.ziqiangxuetang.com/django/django-intro.html
打開pycharm,打開工程tieba,本工程采用的env是virtualenv。來自 ~/.virtualenvs/ py3env_test
可以用Pycharm/Preferences/ 去下載最新的django。我下載的是2.1版本。下載好的django會存放到這個virtualenv的site-packages目錄下。
然后進入到py3env_test , 運行source bin/activate,激活這個虛擬環境
ok,激活后,執行pip3 install django。由于我用pycharm導入的這個框架,所以此處提醒我已經安裝好了。
使用命令創建項目:django-admin.py startproject
myfirstDjangoProject
。這個項目最后會存放到 ~/ 目錄下。可以指定創建目錄到python_test
cd 到 工程 myfirstDjangoProject,然后執行 python manage.py runserver
打開瀏覽器:
Django version 2.0.1, using settings 'myfirstDjangoProject.settings' Starting development server at http://127.0.0.1:8000/
創建mydjango_app ,并且,創建views.py, 創建第一個django應用。
總結一句:第一步,打開虛擬環境;第二步,創建項目(如果已經有項目則cd到項目) ;第三步,到工程里運行項目
去掉提示 migration提醒
#Django 1.7.x 以下版本 python manage.py syncdb # Django 1.7.x 以及上要用 python manage.py migrate
?
over
Django視圖與網址以及進階
參考文檔:https://code.ziqiangxuetang.com/django/django-views-urls.html
參考文檔2:https://code.ziqiangxuetang.com/django/django-views-urls2.html
新建一個APP,名稱為learn
python manage.py startapp learn ``# learn 是一個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', )
我們在learn這個目錄中,把views.py打開,修改其中的源代碼,改成下面的
# coding:utf-8 from django.http import HttpResponse def index(request): return HttpResponse(u"歡迎光臨 自強學堂!")
定義視圖函數相關的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), ]
已經學到QuerySet API 這一章節
python細微語法總結
函數
1. 函數、參數、高階函數、None 位置參數 def add_end(L=None): if L is None: L = [] L.append('END') return L 可變參數 def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum 關鍵字參數 **args 可變參數允許你傳入0個或任意個參數,這些可變參數在函數調用時自動組裝為一個tuple。而關鍵字參數允許你傳入0個或任意個含參數名的參數,這些關鍵字參數在函數內部自動組裝為一個dict 命名關鍵字參數,如果要限制關鍵字參數的名字,就可以用命名關鍵字參數。用*分隔符 分割 如果函數定義中已經有了一個可變參數,后面跟著的命名關鍵字參數就不再需要一個特殊分隔符*了 命名關鍵字參數必須傳入參數名,這和位置參數不同 //總結 必選參數、默認參數、位置參數、可變參數、關鍵字參數、命名關鍵字參數、參數組合 參數定義的順序必須是:必選參數、默認參數、可變參數、命名關鍵字參數和關鍵字參數。 2. list、tuple 3. 高級特性 切片 L = list(range(100)) L[0:3] 同L[:3] L[1:3] L[-2:] L[:10:2] 前10個數,每兩個取一個:[0, 2, 4, 6, 8] 'ABCDEFG'[::2] 迭代 列表生成式 生成器 迭代器 4. 函數式編程 map reduce filter sorted 返回函數 匿名函數: list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) 裝飾器 def now(): ... print('2015-3-25') 假設我們要增強now()函數的功能,比如,在函數調用前后自動打印日志,但又不希望修改now()函數的定義,這種在代碼運行期間動態增加功能的方式,稱之為“裝飾器”(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() 偏函數
模塊
1. 使用模塊 任何模塊代碼的第一個字符串都被視為模塊的文檔注釋 __author__ = 'Michael Liao' 2. 運行 if __name__=='__main__': test() 當我們在命令行運行hello模塊文件時,Python解釋器把一個特殊變量__name__置為__main__,而如果在其他地方導入該hello模塊時,if判斷將失敗。 3. 作用域 public:正常的函數和變量名是公開的(public),可以被直接引用,比如:abc,x123,PI等 __xxx__這樣的變量是特殊變量,可以被直接引用,但是有特殊用途,比如上面的__author__,__name__就是特殊變量 類似_xxx和__xxx這樣的函數或變量就是非公開的(private),不應該被直接引用,比如_abc,__abc等
面向對象
1. __init__方法的第一個參數永遠是self,表示創建的實例本身,因此,在__init__方法內部,就可以把各種屬性綁定到self,因為self就指向創建的實例本身 2.類: 要定義一個方法,除了第一個參數是self外,其他和普通函數一樣。 3. 訪問限制 4. 繼承+多態 5. 獲取對象信息 type() isinstance() 6. __slots__ Python允許在定義class的時候,定義一個特殊的__slots__變量,來限制該class實例能添加的屬性 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
可以匹配一個數字,\w
可以匹配一個字母或數字,\s匹配空格
.
可以匹配任意字符用
*
表示任意個字符(包括0個),用+
表示至少一個字符,用?
表示0個或1個字符,用{n}
表示n個字符,用{n,m}
表示n-m個字符
'-'
是特殊字符,在正則表達式中,要用'\'
轉義要做更精確地匹配,可以用
[]
表示范圍
[0-9a-zA-Z\_]
可以匹配一個數字、字母或者下劃線
A|B
可以匹配A或B
^
表示行的開頭,^\d
表示必須以數字開頭。
$
表示行的結束,\d$
表示必須以數字結束re模塊
強烈建議使用Python的
r
前綴,就不用考慮轉義的問題了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常用內建模塊
datetime & collections & base64 & struct & hashlib & hmac & zip
zip() 函數用于將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的列表 >>>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
該模塊用于解析通過命令行運行的參數 $ python a.py 10 20 解析10 20這些基本參數 該模塊有基本用法, import argparse parser = argparse.ArgumentParser() parser.add_argument('--batch_size', default=100, type=int, help='batch size') #然后 args = parser.parse_args()
python內置函數:http://www.runoob.com/python/python-built-in-functions.html
over
模塊
連接數據庫
#MySQL官方提供了mysql-connector-python驅動,但是安裝的時候需要給pip命令加上參數--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庫學習
參考文獻: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刪除某列,返回刪除的那一列的數據,此處為簡單賦值 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 布爾過濾:df.rain_octsep < 1000 索引:df.iloc[30] 對數據集應用函數: 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) 數據集結構操作 合并數據集: 使用Pandas快速作圖:
ove
Numpy快速入門
Python 學習數據科學或者機器學習,就必須學習 NumPy
1. 創建二位數組、矩陣 2. 多維數組切片 3. 數組屬性 4.
over
TensorFlow入門
機器學習新手入門:https://www.tensorflow.org/get_started/get_started_for_beginners
模型與訓練
模型即特征與標簽之間的關系。對于鳶尾花問題,模型定義了花萼和花瓣測量值與鳶尾花品種之間的關系。一些簡單的模型可以用幾行代數進行描述;比較復雜的機器學習模型則包含大量的交錯數學函數和參數,以至于難以從數學角度進行總結 監督式學習 非監督式學習
獲取示例程序
1. 安裝TensorFlow(使用virtualenv直接導入該pachkage) 2. 安裝Pandas庫 3. 獲取代碼:git clone https://github.com/tensorflow/models 4. cd models/samples/core/get_started/ 5. python premade_estimator.py
高階API:
Estimator
和Dataset
程序流程
1. 導入和解析數據集。 2. 創建特征列以描述數據。 3. 選擇模型類型。 4. 訓練模型。 5. 評估模型的效果。 6. 讓經過訓練的模型進行預測。
?
over