Python 是一門高級編程語言, 它簡單易用,而且人們已經開始發現它的魅力. 對於 Python 菜鳥來說,學習編程絕非容易的事,但一旦掌握了 Python,你可以使用它來完成各種各樣的任務,包括數據分析、機器學習、Web 開發等等. 今天,我們將從不同的角度來闡述 Python 泛菜鳥的各種技術點,幫助你更好的掌握這門編程語言.
一、Python 菜鳥基礎語法
1、Python 環境的搭建
直接去官網下載安裝即可
https://www.python.org/downloads/
2、Python 編寫第一個程序
print(「Hello World!」)
3、Python 聲明變量
# Python 學習變量的使用
counter = 100 # 整型變量
miles = 1000.0 # 浮點型變量
name = "Python" # 字符串變量
print (counter)
print (miles)
print (name)
4、Python 數據類型
#Python 3 支持 int、float、complex(複數)
#Python3.x 支持bytes、str兩種類型的字符串,其中,'b'或'B'前綴表示byte字符串,沒有則表示unicode字符串。
a, b, c, d = 20, 5.5, True, 4+3j
print(type(a), type(b), type(c), type(d))
5、Python 運算符
#Python算術運算符
print(5+4) #加法
print(4.3-2) #減法
print(3*7) #乘法
print(2/4) #除法,得到一個浮點數
print(2//4) #除法,得到一個整數
print(17%3) #取余
print(2**5) #乘方
#Python比較運算符
a, b = 10, 20
print("a = ", a)
print("b = ", b)
print("a == b: ", a == b) # 等於
print("a != b: ", a != b) # 不等於
print("a > b: ", a > b) # 大於
print("a < b: ", a = b: ", a >= b) # 大於等於
print("a <= b: ", a <= b) # 小於等於
#Python賦值運算符
a = 21
b = 10
c = 0
c = a + b
print("c = a + b: ", c) # 賦值運算符
c += a
print("c += a : ", c)
c *= a
print("c *= a : ", c)
c /= a
print("c /= a : ", c)
c = 2
c %= a
print("c %= a : ", c)
c **= a
print("c **= a : ", c)
c //= a
print("c //= a : ", c)
二、Python 數據分析
1、NumPy 基礎操作
import numpy as np
# 創建新的數組
x = np.array([1, 2, 3, 4, 5])
# 打印數組
print(x)
# 將列錶轉化為數組
y = np.array([[1, 2, 3], [4, 5, 6]])
# 打印多維數組
print(y)
# 打印數組大小
print("數組大小:", y.shape)
# 訪問數組元素(與 Python 列表類似)
print("y[1,2]為:", y[1, 2])
2、Pandas 數據分析
import pandas as pd
# 創造一個字典使'Name'作為關鍵字
df = pd.DataFrame({'Name': ['John', 'Alice', 'Bob'],
'Age': [20, 21, 22],
'Gender': ['M', 'F', 'M']})
# 輸出數據框對象
print(df)
3、Matplotlib 數據可視化
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y = np.sin(x)
# 繪圖
plt.plot(x, y)
# 繪圖標題
plt.title('y=sin(x)')
# x、y軸標題
plt.xlabel('x')
plt.ylabel('y')
# 顯示
plt.show()
三、Python Web 開發
1、Flask 基於 Python 的 Web 開發框架
from flask import Flask, render_template,request,redirect,url_for,session
app = Flask(__name__)
app.secret_key = 'demo_key' # session的密鑰
todos = []
@app.route('/')
def index():
return render_template('index.html', todos=todos)
@app.route('/add', methods=['POST'])
def add():
# 用戶輸入的任務列表加入到todos列表中
content = request.form['content']
todos.append(content)
return redirect(url_for('index'))
2、Django
# 安裝django
pip install django==2.0
# 創建並運行django項目
django-admin startproject firstproject
python manage.py runserver
3、Pyramid
# 安裝 Pyramid
pip install pyramid
# 創建 Pyramid項目
pcreate -s starter myproject
# 安裝所需的依賴項
cd myproject && pip install -e .
# 運行 Pyramid
pserve development.ini
# 瀏覽器中查看
localhost:6543
四、Python 機器學習
1、scikit-learn
from sklearn import datasets
# 導入數據集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 劃分為測試和訓練數據集
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=33)
# Z-score特徵規範化
from sklearn.preprocessing import StandardScaler
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
# 使用KNN分類器
from sklearn.neighbors import KNeighborsClassifier
knc = KNeighborsClassifier()
knc.fit(X_train, y_train)
y_predict = knc.predict(X_test)
# 模型評估
from sklearn.metrics import classification_report
print('Accuracy: {}\n'.format(knc.score(X_test, y_test)))
print(classification_report(y_test, y_predict, target_names=iris.target_names))
# 數據可視化
import matplotlib.pyplot as plt
plt.scatter(X[y==0, 0], X[y==0, 1], color='red', marker='o', label='setosa')
plt.scatter(X[y==1, 0], X[y==1, 1], color='blue', marker='x', label='versicolor')
plt.scatter(X[y==2, 0], X[y==2, 1], color='green', marker='+', label='virginica')
plt.legend(loc='upper left')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.show()
2、TensorFlow
import tensorflow as tf
# 創建常量
a = tf.constant(5)
b = tf.constant(2)
c = tf.constant(3)
# 使用add()函數將兩個常量相加
d = tf.add(a, b)
# 使用multiply()函數將常量d乘3
e = tf.multiply(d, 3)
# 使用subtract()函數將常量e減c
f = tf.subtract(e, c)
# 創建會話並傳遞f來執行計算圖操作
with tf.Session() as sess:
print(sess.run(f))
3、Keras
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
# 初始化模型
model = Sequential()
# 添加輸入層和隱藏層
model.add(Dense(units=64, input_dim=100))
model.add(Activation('relu'))
# 添加輸出層
model.add(Dense(units=10))
model.add(Activation('softmax'))
# 編譯模型
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
# 擬合模型
model.fit(X_train, y_train, epochs=20, batch_size=128)
# 評估模型
loss_and_metrics = model.evaluate(X_test, y_test, batch_size=128)
五、Python 爬蟲
1、Requests 爬蟲庫
import requests
# 發送 GET 請求
r = requests.get('http://www.baidu.com')
# 打印響應正文
print(r.text)
# 打印響應狀態碼
print(r.status_code)
# 打印響應頭部
print(r.headers)
2、BeautifulSoup 網頁解析庫
import requests
from bs4 import BeautifulSoup
# 發送 GET 請求
r = requests.get('http://www.baidu.com')
# 解析 HTML 代碼
soup = BeautifulSoup(r.text, 'html.parser')
# 檢索並打印所有鏈接
for link in soup.find_all('a'):
print(link.get('href'))
3、Scrapy 爬蟲框架
# 安裝 Scrapy
pip install scrapy
# 創建新項目
scrapy startproject example
# 創建新爬蟲
scrapy genspider myspider example.com
# 運行爬蟲
scrapy crawl myspider
六、Python 性能優化
1、使用生成器替代列表
# 使用列表
def read_file():
with open('huge_text_file.txt') as f:
lines = f.readlines()
for line in lines:
yield line
# 使用生成器
def read_file():
with open('huge_text_file.txt') as f:
for line in f:
yield line
2、使用 itertools 模塊優化代碼
import itertools
# 串行執行
for i in itertools.chain((1,2,3),('a','b','c')):
print(i)
# 並行執行
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
for result in executor.map(do_something, alist):
print(result)
3、使用 functools.lru_cache() 優化並實現記憶化
import functools
@functools.lru_cache()
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
# 獲得斐波那契數列的第10項
print(fib(10))
Python 可以適用來完成各種各樣的工作,用來開發數據分析、機器學習、Web 應用和爬蟲等等都非常方便。希望以上內容對你理解和掌握 Python 的技能有所幫助!
原創文章,作者:QJBUB,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/369634.html