Python 說明
MAP
- crawler
- # Request
- # BeautifulSoup:(HTML 靜態解析)
- # Selenium:web瀏覽器的自動化
- # Scrapy
- # XPath expression
- # CSS selectors
- # javascript disable/enable
packages
- # Packages list:packages list
- # Packages matplotlib.pyplot:繪圖
- # plotly:繪圖
- # matplotlib.pyplot 3D:3D繪圖
- # Seaborn:matplotlib 的高階 API(透過封裝的方式大幅度地簡化許多設定上的細節)
- # Numpy
- # SciPy
- # Pandas
- # sympy
- # Tkinter:Tk GUI
- # Packages excell:
- # Connect to google sheet:google 試算表
- # scikit-learn:用於Python程式語言的自由軟體機器學習庫
function
Web Framework : Django
GUI : PyQt
tool
- # Google Colab:python 雲端開發平台
- # Jupyter Notebook:
- # PyCharm
select python
1 | # check which python |
基本
import
1 | # 一般 import |
pass
1 | pass |
運算元
1 | print(f'10 == 10 : {10 == 10}') |
1 | >>> type(3.5) |
global function and variable
1 | import os |
條件式
1 | a = 200 |
1 | # match |
迴圈
1 | fruits = ["apple", "banana", "cherry"] |
function
1 | # comment |
classes
example
1 | # simple |
1 | # example |
class method
1 | # class method |
1 | # class method - create instance |
inheritance
1 | # inheritance |
operation overload
1 | # operation overload |
非被引用才執行
1 | def main(): |
create library
1 | # sayings.py |
1 | # say.py |
1 | python say.py Robert |
變數
- array VS list
- array 屬於 Python 模組 numpy 裡的一種數據類型,所包含的所有元素類型都必須相同
- list 是 Python 內建的數據類型,可以包含不同的元素類型
None(空值)
1 | if resp is None: |
變數與型態
1 | money = 100 |
string
1 | # join |
1 | greet = "hi" + " " + " " + "Robert" |
list
1 | # remove 1 item |
tuple - 不能修改的List
Dictionaries
1 | MENU = { |
set() 集合
基本
1 | # 集合 set() |
1 | # set() : 儲存不重複 |
集合操作
1 | # 集合操作 |
子集(subset), 宇集(superset) and 補集(屬於A, 但不在B)
1 | # 子集(subset), 宇集(superset) and 補集(屬於A, 但不在B) |
集合新增刪除
1 | # 集合新增刪除 |
sympy 模組與集合
集合相乘 - 笛卡兒積
1 | # 集合相乘 - 笛卡兒積 |
syntax
anonymous functions
1 | testGreedy(foods, maxUnits, |
1 | >>> f1 = lambda x: x |
if + assign value
1 | import re |
class print function : string
1 | class Food(object): |
@classmethod
1 | class MyClass: |
dict - key by tuple
1 | self.q = dict() |
assert
1 | def divide(a, b): |
code style
1 | # install |
global - 在 function global variable 內寫入時要加 global variable
1 | # bank.py |
constant - 大寫表常數,但使用上還是可以被更改
1 | # constant |
1 | # constant |
unpack - *:list, **:dict., (*args, **kwargs): multi parameter
1 | # unpack.py |
1 | # unpack.py |
1 | # unpack.py |
IO
input
1 | coin = float(input(' How many quarters?:')) |
1 | # print(*objects, sep=' ', end='\n', file=None, flush=False) |
file I/O
1 | # access_mode |
1 | # remove file |
1 | import os |
sorted
1 | # sorted(iterable, /, *, key=None, reverse=False) |
zip
1 | # example |
copy
1 | # copy to new variable |
items
1 | # self.q.items() returns a view of the dictionary's key-value pairs, |
tuple - list –> tuple
1 | q = self.q[tuple(state), move] |
specific operation
get page
1 | import requests |
get local ip & ip location
1 | def get_local_ip(): |
Unit test - pytest
case 1
1 | # calculator.py |
1 | # test_calculator.py |
1 | pytest .\test_calculator.py |
case 2
1 | # hello.py |
1 | # test_hello.py |
1 | PS D:\work\run\python\python_100ds\cs50p> pytest .\test_hello.py |
multi test
1 | mkdir test |
Built-in function
csv
1 | ## students.csv |
1 | # students.py - csv write |
1 | # students.py - csv write by DictWriter |
1 | import csv |
1 | import csv |
simple function
1 | abs(x) |
round
1 | # round(number, ndigits=None)¶ |
set() 函数 - 創建一個無序不重複元素集
1 | def get_author_ids(posts, pattern): |
json
1 | # json |
1 | import json |
1 | # json to dict |
SQLite
GUI SQLite tool:DB Browser for SQLite
新增資料表,資料
1 | # 新增資料表,資料 |
資料查詢
1 | # 資料查詢 |
資料修改
1 | # 資料修改 |
other 1
1 | # for SQlite |
other 2
1 | import csv |
os
1 | import os |
timedate
1 | import datetime |
time
1 | import time |
re
1 | import re |
quote/unquote
1 | # 修正中文 show 亂碼 |
urllib - dowload file
1 | import urllib |
random
1 | import random |
1 | import random |
argparse
1 | # meows.py |
map, list comprehensions
1 | # map, list comprehensions |
filetr
1 | # filter |
dictionary comprehensions
1 | # dictionary comprehensions |
1 | students = ["Hermione", "Harry", "Ron"] |
enumerate
1 | # enumerate |
generators - yield
1 | # generators |
計算函數
pow() 指數運算
1 | >>> pow(4,3) |
special function
put password to local file
pipelines.py
1 | # for mongodb client link |
mongodb_altas.py
1 | mogodb_link = "m......" |
delete file if exist
1 | # delete imdb if exist |
MongoDB
1 | # for MongoDB |
exception
1 | # simple case |
1 | # sqlite3 example |
download image
1 | from PIL import Image |
URL unicode 轉成中文
1 | # URL unicode 轉成中文 |
非同步模組 - concurrent.futures
1 | # 非同步模組 - concurrent.futures |
windows set/show evn
1 | # window set/show evn by cmd |
detect image type
1 | def detect_image_type(content): |
itertools
1 | import itertools |
math
1 | import math |
Packages
list
1 | # SciPy Python : 演算法庫和數學工具包 |
sys
1 | # sys module |
w3lib - A Python library of web-related functions
1 | # add for splash user+password(run Aquarium) |
wget - downloa file
1 | import os |
matplotlib.pyplot
some special
use windows font + show 負號
1 | import matplotlib.pyplot as plt |
plot add text
1 | # 列出利潤 48 萬 |
支援 LaTeX語法
show - $x_{1}$
1 | plt.xlabel(r'$x_{1}$', fontsize=14) |
繪散點圓圈
1 | # 用圓圈繪製支援向量 |
x, y軸距長度一致
1 | # x, y軸距長度一致 |
表格顯示範圍
1 | # 表格顯示範圍 x:0~20,y:0~20 |
顯示顏色條
1 | # 使用隨機數據陣列產生圖像 |
更改視角
1 | # 更改視角 |
畫水平線
1 | # 畫水平線 |
DataFrame 畫圖
# 了解特徵對模型的重要性1 | # 長條圖 |
獲取當前的坐標軸對象
1 | # 獲取當前的坐標軸對象 |
獲得當前繪圖區域(axes)的 x 軸和 y 軸的範圍
1 | xlim = ax.get_xlim() |
將子圖的陣列進行扁平化處理(原sub 為2*2)
1 | fig, sub = plt.subplots(2, 2, figsize=(10, 10)) |
example
折線圖
1 | # 折線圖 |
長條圖
1 | # 長條圖 |
橫條圖
1 | # 橫條圖 |
堆疊長條圖
1 | # 堆疊長條圖 |
並列長條圖
1 | # 並列長條圖 |
圓形圖
1 | # 圓形圖 |
直方圖(值的統計)
1 | # 直方圖(值的統計) |
直方圖(值的統計) - 概率密度計算
1 | # 直方圖(值的統計) - 概率密度計算 |
散佈圖
1 | # 散佈圖 |
繪製等高線圖
- plt.contourf() : 繪製等高線同時填充
- plt.contour() : 繪製等高線不填充
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28# 2D 平面上使用等高線圖來表示一個二次函數的高度
import numpy as np
import matplotlib.pyplot as plt
# 建立一個網格
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
XX, YY = np.meshgrid(x, y)
# 定義一個二次函數 Z = X^2 + Y^2
Z = XX**2 + YY**2
# 創建一個圖形和軸
fig, ax = plt.subplots()
# 使用 contour 畫出等高線
contour = ax.contour(XX, YY, Z, colors='b', levels=[10, 20, 30], alpha=0.8, linestyles=['--', '-', '--'])
# 添加等高線的標籤
ax.clabel(contour, inline=True, fontsize=10)
# 設置標題和軸標籤
ax.set_title('Contour Plot Example')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
# 顯示圖形
plt.show()
箱型圖
# 特徵箱形圖皮爾遜相關係數熱圖
# 繪製皮爾遜相關係數熱圖設定圖表區
1 | # 設定圖表區 |
繪製多子圖
# 繪製KNN迴歸曲線1 | # 繪製多子圖 |
欄列排列多張圖
1 | # 欄列排列多張圖 |
相對位置排列多張圖
1 | # 相對位置排列多張圖 |
圖書分類銷售分析圖
1 | # 圖書分類銷售分析圖 |
basic
1 | # import pylab as plt |
複利繪圖
1 | import matplotlib.pyplot as plt |
requests
install
1 | pip3 install requests |
get tunes song
1 | # python itunes.py weezer |
Pillow
costume1.gif
costume2.gif
costumes.gif
costume.py
1 | import sys |
generate costumes.gif
1 | python costumes.py costume1.gif costume2.gif |
re - regular expression
pythex
example
1 | # validate.py |
basic function
1 | import re |
1 | # 擷取數字 |
capture
1 | # format.py |
get twitter name from URL
1 | # twitter.py |
excel
1 | # excel (only support .xlsx) |
1 | # write excel sheet tile |
1 | # create sheet |
mypy
1 | # meows.py |
Docstring : just prepare for gernerate document
1 | # meows.py |
coesay + audio
1 | # say.py |
Ref
- python time module
- Regular expression operations
- Python Exception
- Python Built-in Functions
- Regular expression operations
- Classes
- class int
- class list
- Parser for command-line arguments
- Data model:Special method names
- enumerate
- map
- filter
- Python requests
- PEP 8
- pycodestyle
- pytest
- Pillow
- mypy
- Docstring
- 使用 WITH AS
- 讀寫JSON數據
- set() 函数
- DB Browser for SQLite
- chercher.tech
- Python SQLite tutorial using sqlite3
- TensorFlow