Python 的語法簡單且接近自然語言,即使是程式設計新手也能快速上手,降低了學習的門檻。
Python 提供了廣泛的標準函式庫,涵蓋網路、數據處理、圖形界面等多方面。此外,強大的第三方生態系如 NumPy、Pandas、TensorFlow 使 Python 成為多功能的開發工具。
Python 是跨平台的語言,無論是 Windows、macOS 還是 Linux,都能執行相同的 Python 程式,極大提高了開發的靈活性。
Python 在多個領域中發揮重要作用,例如資料科學、人工智慧、網頁開發、自動化腳本和遊戲開發等,讓開發者可以用一種語言處理多種需求。
Python 擁有一個龐大的全球社群,無論是初學者還是資深開發者,都能輕易找到教學資源、討論群組和技術支持。
Python 提供了直觀的語法和強大的工具,讓開發者能更快地實現程式設計,縮短產品的開發週期。
Anaconda 是一個開放源碼的 Python 和 R 編程平台,專為科學計算設計,包括數據科學、機器學習、人工智慧和大數據分析等應用。
Anaconda 適合以下領域的使用者:
以下是使用者常遇到的問題:
可以在終端機中輸入 conda update conda
和 conda update anaconda
。
Anaconda 是一個整合了 Python 的數據科學平台,內建了多種工具和庫,而 Python 是一種程式語言。
Jupyter 是一個開放源碼的交互式計算環境,支援多種程式語言,主要用於數據科學、機器學習和學術研究。
Jupyter 被廣泛應用於以下領域:
jupyter notebook
啟動 Jupyter Notebook。前往 Visual Studio Code官方網站,下載並安裝適合您作業系統的版本。
在Visual Studio Code中,透過以下步驟安裝Python擴展:
確保系統已安裝Python。可以從 Python官方網站 下載並安裝。
安裝完成後,在命令列輸入以下指令確認安裝成功:
python --version
# 或
python3 --version
打開您的Python專案或檔案,點擊Visual Studio Code右下角的「Python」狀態欄,選擇適當的Python解譯器。
在編輯器中開啟Python檔案,使用以下方式執行程式:
Ctrl + Shift + P
,搜尋「Run Python File」並執行。如果需要安裝第三方套件,可以使用內建終端機輸入:
pip install 套件名稱
透過Python擴展提供的功能,可享受自動完成與強大的除錯工具:
以下是幾個常用快捷鍵:
Ctrl + F5
Ctrl + Shift + P
Shift + Alt + F
Ctrl + `
若需要在執行Python程式時傳遞參數,可以透過設定 launch.json
完成:
launch.json
文件中修改相關設定。以下是一個範例配置,包含程式路徑和執行時的參數:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Run with Arguments",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/main.py", // 程式路徑
"console": "integratedTerminal", // 終端類型
"args": ["arg1", "arg2", "--option", "value"] // 傳遞參數
}
]
}
在 args
中可以傳遞命令列參數,例如:
arg1
和 arg2
為位置參數。--option
和 value
為帶有選項的參數。使用 sys.argv
來讀取命令列傳遞的參數:
import sys
print("所有參數:", sys.argv)
if len(sys.argv) > 1:
print("第一個參數:", sys.argv[1])
print("第二個參數:", sys.argv[2])
假設程式為:
python main.py arg1 arg2 --option value
執行結果:
所有參數: ['main.py', 'arg1', 'arg2', '--option', 'value']
第一個參數: arg1
第二個參數: arg2
1. 安裝 Python Extension 擴展。
2. 在 VS Code 中開啟您的 Python 專案。
3. 按下 F5
或點擊左側活動欄的 Debug 圖示。
1. 點擊 Debug 面板中的「新增配置」。
2. 選擇 Python,系統會自動生成一個 launch.json
。
{ "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal" } ] }
1. 在程式碼行號旁點擊以新增中斷點。
2. 可使用條件中斷點:右鍵點擊中斷點並選擇「編輯條件」。
F10
跳過函式。F11
進入函式內部。Shift+F11
跳出函式。1. 在 Debug 面板的「變數」區域檢視目前變數狀態。
2. 可在「監視」區域手動加入特定表達式。
1. 在 Debug Console 中輸入 Python 指令以即時檢查程式狀態。
2. 可執行變數查詢、呼叫函式等操作。
pip --version
pip install 套件名稱
例如:pip install requests
pip install --upgrade 套件名稱
例如:pip install --upgrade requests
pip list
pip uninstall 套件名稱
例如:pip uninstall requests
pip list --outdated
pip install 套件名稱==版本號
例如:pip install requests==2.26.0
pip install -r requirements.txt
使用 requirements.txt
檔案,列出所有需要的套件名稱及版本。
pip freeze > requirements.txt
此指令會將當前環境中的套件和版本導出為需求檔案。
pip cache purge
清理 pip 的快取資料夾以釋放磁碟空間。
解決方法:檢查是否已安裝 Python,並確認 Python 的安裝目錄已加入系統的 PATH 環境變數中。
解決方法:嘗試加上 --user
參數,例如:pip install 套件名稱 --user
解決方法:確認網路是否正常,或嘗試使用國內的鏡像源,例如:pip install 套件名稱 -i https://pypi.tuna.tsinghua.edu.cn/simple
venv
或 virtualenv
),避免全域安裝套件產生衝突。requirements.txt
來管理依賴關係。http-v2
目錄中,以便未來安裝相同套件時不需要再次下載。pip cache dir
查看目前緩存目錄。pip cache purge
清除所有緩存資料。http-v2
資料夾的內容,但這樣會使 pip 下次安裝相關套件時重新下載檔案。--no-cache-dir
參數,例如:
pip install package_name --no-cache-dir
。
確保已安裝 Python 並將其加入系統環境變數,然後下載並安裝 Visual Studio Code。
開啟 Visual Studio Code,點擊左側的 Extensions 圖示,搜尋 Python,然後安裝 Microsoft 提供的 Python 擴充套件。
在終端機輸入以下指令來確認 Python 的安裝路徑:
which python
或(Windows 系統):
where python
在 Visual Studio Code 中,按 Ctrl + Shift + P,輸入並選擇 Python: Select Interpreter。
在清單中選擇正確的 Python 路徑。如果未顯示,請手動輸入完整路徑。
開啟終端機並執行 python --version
來確認選定的 Python 解釋器版本正確。
如果需要特定專案的 Python 路徑,可以在專案根目錄新增 .vscode/settings.json
檔案,並加入以下內容:
{
"python.pythonPath": "你的 Python 完整路徑"
}
替換 你的 Python 完整路徑
為實際路徑。
在 Python 中,陣列是一種用於存儲多個相同類型元素的資料結構。雖然 Python 本身並沒有內建的陣列型別,但可以使用 list
或 array
模組來實現類似的功能。
list
是 Python 的內建資料結構,可以儲存多種類型的資料,但也可以用來模擬陣列。
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 輸出: 1
如果需要真正的陣列(所有元素必須是相同類型),可以使用 array
模組。
import array
my_array = array.array('i', [1, 2, 3, 4, 5])
print(my_array[0]) # 輸出: 1
在這裡,'i'
表示陣列中的元素是整數。
以下是一些基本操作:
my_array.append(6)
my_array.remove(3)
len(my_array)
對於需要進行數值運算的情況,numpy
提供了更強大的陣列支援。
import numpy as np
my_numpy_array = np.array([1, 2, 3, 4, 5])
print(my_numpy_array[0]) # 輸出: 1
NumPy 陣列支援多維資料與向量化運算,非常適合處理大量數據。
Python 提供多種方式來實現陣列功能,list
適用於一般情況,array
模組適合需要相同類型元素的情況,而 numpy
是科學計算的首選工具。
在 Python 中,list
是動態資料結構,可以輕鬆進行元素的新增與移除。
可以使用以下方法新增元素:
append()
: 在列表的末尾新增一個元素。insert()
: 在指定索引位置插入一個元素。extend()
: 將另一個列表的元素追加到現有列表中。# 新增元素示例
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
my_list.insert(1, 10) # [1, 10, 2, 3, 4]
my_list.extend([5, 6]) # [1, 10, 2, 3, 4, 5, 6]
可以使用以下方法移除元素:
pop()
: 根據索引移除元素,預設移除最後一個元素。remove()
: 根據值移除第一個匹配的元素。clear()
: 移除列表中的所有元素。# 移除元素示例
my_list = [1, 2, 3, 4, 5]
my_list.pop() # [1, 2, 3, 4]
my_list.remove(2) # [1, 3, 4]
my_list.clear() # []
對於需要相同類型元素的情況,可以使用 array
模組。
append()
和 extend()
方法適用於 array
模組。
import array
my_array = array.array('i', [1, 2, 3])
my_array.append(4) # [1, 2, 3, 4]
my_array.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
remove()
和 pop()
方法可用於 array
模組。
# 移除元素示例
my_array = array.array('i', [1, 2, 3, 4])
my_array.remove(2) # [1, 3, 4]
my_array.pop() # [1, 3]
Python 提供了多種方法來實現陣列的動態增減,list
與 array
模組分別適合不同需求。對於更多功能需求,也可以考慮使用 numpy
。
isdigit()
方法可以用於檢查字串是否只包含數字字符。
# 示例
string = "12345"
if string.isdigit():
print("是數字")
else:
print("不是數字")
注意:isdigit()
無法處理小數點或負號。
如果需要檢查帶有小數點的字串,可以先移除小數點再使用 isdigit()
。
# 示例
string = "123.45"
if string.replace(".", "").isdigit():
print("是數字")
else:
print("不是數字")
此方法不適用於負數。
最通用的方法是嘗試將字串轉換為浮點數或整數,並捕捉轉換失敗的異常。
# 示例
string = "-123.45"
try:
float(string) # 可以改用 int(string) 來檢查整數
print("是數字")
except ValueError:
print("不是數字")
正則表達式可以精確匹配數字,包括整數、小數與負數。
# 示例
import re
string = "-123.45"
pattern = r"^-?\d+(\.\d+)?$"
if re.match(pattern, string):
print("是數字")
else:
print("不是數字")
對於簡單情況,可使用 isdigit()
。對於更複雜的情況(如處理小數或負數),建議使用 try-except
或正則表達式。
給定一個字串 str1
,我們希望找到在 strA
或 strB
出現之前的部分。例如:
str1 = "Hello World, this is a test. Stop here or continue."
strA = "Stop"
strB = "continue"
目標是獲取 "Hello World, this is a test. "
。
re.split()
可以根據多個關鍵字拆分字串,並取第一部分:
import re
def get_substring_before(text, strA, strB):
result = re.split(f"{re.escape(strA)}|{re.escape(strB)}", text, maxsplit=1)[0]
return result
str1 = "Hello World, this is a test. Stop here or continue."
strA = "Stop"
strB = "continue"
print(get_substring_before(str1, strA, strB)) # "Hello World, this is a test. "
re.search()
可以用來匹配 strA
或 strB
,並取得匹配前的內容:
import re
def get_substring_before(text, strA, strB):
match = re.search(f"{re.escape(strA)}|{re.escape(strB)}", text)
return text[:match.start()] if match else text
str1 = "Hello World, this is a test. Stop here or continue."
print(get_substring_before(str1, "Stop", "continue")) # "Hello World, this is a test. "
find()
方法可以手動搜尋最早出現的 strA
或 strB
,然後擷取對應部分:
def get_substring_before(text, strA, strB):
indexA = text.find(strA)
indexB = text.find(strB)
indices = [i for i in [indexA, indexB] if i != -1]
first_index = min(indices, default=len(text))
return text[:first_index]
str1 = "Hello World, this is a test. Stop here or continue."
print(get_substring_before(str1, "Stop", "continue")) # "Hello World, this is a test. "
re.split()
最簡單,適合單次查找。re.search()
提供更靈活的正則匹配。find()
方法最有效率,適用於簡單的字串處理。
Python 的 re.match
是正則表達式模組中的一個函式,用於從字串的開頭進行匹配。
如果匹配成功,則返回一個 Match
物件;否則返回 None
。
re.match(pattern, string, flags=0)
參數說明:
pattern
:要匹配的正則表達式。string
:要被檢查的字串。flags
:可選參數,用於修改匹配行為,例如 re.IGNORECASE
。group(n)
:返回第 n
個捕獲的子組,n=0
返回整個匹配。start()
:返回匹配的起始位置。end()
:返回匹配的結束位置。span()
:返回匹配的範圍 (起始, 結束)。import re
# 定義一個字串
text = "123 Hello World!"
# 使用 re.match 從開頭匹配數字
match = re.match(r"(\d+)\s+(.*)", text)
if match:
print(f"整個匹配結果: {match.group(0)}") # 123 Hello World!
print(f"數字部分: {match.group(1)}") # 123
print(f"文字部分: {match.group(2)}") # Hello World!
else:
print("匹配失敗")
整個匹配結果: 123 Hello World!
數字部分: 123
文字部分: Hello World!
re.match
只從字串開頭進行匹配,若開頭不符合,則返回 None
。re.search
或 re.findall
。
正則表達式(Regular Expression,簡稱 Regex)是一種用於描述字串匹配規則的語法,常用於搜尋、替換或驗證字串。
在 Python 的 re
模組中,pattern
就是定義這些規則的核心部分。
\d
:匹配任何數字(0-9)。\D
:匹配任何非數字。\w
:匹配任何單字字元(字母、數字、底線)。\W
:匹配任何非單字字元。\s
:匹配任何空白字元(空格、Tab 等)。\S
:匹配任何非空白字元。.
:匹配除換行符(\n
)以外的任何單個字元。*
:匹配前一個表達式 0 次或多次。+
:匹配前一個表達式 1 次或多次。?
:匹配前一個表達式 0 次或 1 次。{n}
:匹配前一個表達式剛好 n 次。{n,}
:匹配前一個表達式至少 n 次。{n,m}
:匹配前一個表達式至少 n 次,但不超過 m 次。^
:匹配字串的開頭。$
:匹配字串的結尾。\b
:匹配單字邊界(如單詞的開頭或結尾)。\B
:匹配非單字邊界。(...)
:分組,捕獲括號內的內容。|
:邏輯「或」,如 a|b
匹配 a
或 b
。(?:...)
:分組但不捕獲內容。(?=...)
:正向環視,匹配後面必須是指定內容。(?!...)
:負向環視,匹配後面不能是指定內容。(?<=...)
:正向回顧,匹配前面必須是指定內容。(?<!...)
:負向回顧,匹配前面不能是指定內容。import re
# 例子 1:匹配數字開頭的內容
pattern = r"^\d+"
text = "123abc"
match = re.match(pattern, text)
if match:
print(f"匹配結果: {match.group()}") # 輸出: 123
# 例子 2:匹配數字後的文字
pattern = r"(\d+)\s+(.*)"
text = "123 Hello World"
match = re.match(pattern, text)
if match:
print(f"數字部分: {match.group(1)}") # 輸出: 123
print(f"文字部分: {match.group(2)}") # 輸出: Hello World
re.search()
用於在字串中搜尋符合正則表達式的第一個匹配項,並回傳 Match
物件,如果沒有匹配則回傳 None
。
import re
text = "Hello 2024!"
match = re.search(r"\d+", text)
if match:
print("找到數字:", match.group()) # 2024
當 re.search()
找到匹配時,會返回 Match
物件,可透過以下方法存取資訊:
group()
:回傳匹配的字串start()
:匹配的起始索引end()
:匹配的結束索引span()
:返回 (start, end) 索引範圍import re
text = "Python 3.10 is great!"
match = re.search(r"\d+\.\d+", text)
if match:
print("匹配內容:", match.group()) # 3.10
print("起始索引:", match.start()) # 7
print("結束索引:", match.end()) # 11
print("範圍:", match.span()) # (7, 11)
透過括號 ()
來建立群組,並使用 group(n)
來提取對應的匹配內容。
import re
text = "John Doe, Age: 25"
match = re.search(r"(\w+) (\w+), Age: (\d+)", text)
if match:
print("姓氏:", match.group(1)) # John
print("名字:", match.group(2)) # Doe
print("年齡:", match.group(3)) # 25
re.search()
只回傳第一個匹配的結果,而 re.findall()
會回傳所有匹配結果。
import re
text = "Price: $10, Discount: $2, Tax: $1"
match = re.search(r"\$\d+", text)
print("re.search:", match.group()) # $10
matches = re.findall(r"\$\d+", text)
print("re.findall:", matches) # ['$10', '$2', '$1']
re.search()
適合用來找到第一個匹配的結果,並能透過 Match
物件獲取詳細資訊。對於多個匹配結果,則可使用 re.findall()
。
在正則表達式中,(...)
會捕獲匹配內容,並存入 group(n)
,但 (?:...)
只用來組織結構,不會影響群組編號,因此匹配速度更快。
如果在正則表達式中使用 ()
來組織匹配條件,會影響 group(n)
的編號。使用 (?:...)
則可確保群組索引不變。
import re
text = "2024-03-12"
pattern = r"(\d{4})-(?:\d{2})-(\d{2})"
match = re.search(pattern, text)
print(match.group(1)) # 2024
print(match.group(2)) # 12
使用 (?:...|...)
可以讓 |
運算符影響匹配內容,但不影響群組存取。
import re
text = "bar123"
pattern = r"(?:foo|bar|baz)\d+"
match = re.search(pattern, text)
print(match.group()) # bar123
在解析 Chrome 參數時,使用 (?:...)
可確保匹配格式不影響群組編號。
import re
cmdline = '--user-data-dir="C:\\Users\\moirg\\AppData\\Local\\Google\\Chrome\\User Data"'
match = re.search(r'--user-data-dir=(?:"([^"]+)"|(\S+))', cmdline)
user_data_dir = match.group(1) or match.group(2)
print(user_data_dir) # C:\Users\moirg\AppData\Local\Google\Chrome\User Data
(?:...)
在正則表達式中能提高效能,避免影響群組索引,並適用於 |
運算及特定條件匹配,使程式碼更高效且清晰。
class MyClass: def __init__(self, value): self.value = value def display(self): print(f"Value: {self.value}") obj = MyClass(10) obj.display() # 輸出: Value: 10
靜態方法使用 `@staticmethod` 裝飾器定義,與類別和物件無關,不能訪問類別屬性或物件屬性。適用於一些工具性功能:
class MyClass: @staticmethod def add(a, b): return a + b result = MyClass.add(5, 3) print(result) # 輸出: 8
類別方法使用 `@classmethod` 裝飾器定義,第一個參數是類別本身(通常命名為 `cls`),可以訪問類別屬性:
class MyClass: count = 0 @classmethod def increment_count(cls): cls.count += 1 MyClass.increment_count() print(MyClass.count) # 輸出: 1
Python 支援類別繼承,子類可以繼承父類的屬性和方法,並覆寫父類方法:
class Parent: def greet(self): print("Hello from Parent!") class Child(Parent): def greet(self): print("Hello from Child!") obj = Child() obj.greet() # 輸出: Hello from Child!
類別屬性是屬於整個類別的,所有物件共享;物件屬性則屬於每個物件:
class MyClass: class_attr = "I am a class attribute" def __init__(self, value): self.instance_attr = value obj1 = MyClass(10) obj2 = MyClass(20) print(MyClass.class_attr) # 輸出: I am a class attribute print(obj1.instance_attr) # 輸出: 10 print(obj2.instance_attr) # 輸出: 20
Python 中的所有類別都默認繼承自 `object`,這是一個內建的基類,提供一些基本方法,例如 `__str__` 和 `__eq__`:
class MyClass(object): def __init__(self, value): self.value = value def __str__(self): return f"MyClass with value {self.value}" obj = MyClass(5) print(obj) # 輸出: MyClass with value 5
在 Python 中,類別繼承允許子類(Derived Class)繼承父類(Base Class)的屬性和方法,實現代碼重用。例如:
class Parent: def greet(self): print("Hello from Parent!") class Child(Parent): pass c = Child() c.greet() # 輸出: Hello from Parent!
子類可以覆寫(Override)父類的方法,改寫其功能:
class Parent: def greet(self): print("Hello from Parent!") class Child(Parent): def greet(self): print("Hello from Child!") c = Child() c.greet() # 輸出: Hello from Child!
在子類中可以透過 `super()` 呼叫父類的方法,並在父類行為基礎上擴展:
class Parent: def greet(self): print("Hello from Parent!") class Child(Parent): def greet(self): super().greet() print("Hello from Child!") c = Child() c.greet() # 輸出: # Hello from Parent! # Hello from Child!
Python 支援多重繼承,子類可以同時繼承多個父類:
class Parent1: def greet(self): print("Hello from Parent1!") class Parent2: def greet(self): print("Hello from Parent2!") class Child(Parent1, Parent2): pass c = Child() c.greet() # 輸出: Hello from Parent1! (依據繼承順序)
多重繼承使用 MRO(Method Resolution Order)確定方法的解析順序。可以使用 `__mro__` 屬性檢查:
print(Child.__mro__) # 輸出: (, , , )
使用 `abc` 模組定義抽象基類(Abstract Base Class),強制子類實現特定方法:
from abc import ABC, abstractmethod class AbstractParent(ABC): @abstractmethod def greet(self): pass class Child(AbstractParent): def greet(self): print("Hello from Child!") c = Child() c.greet() # 輸出: Hello from Child!
class ClassB:
def greet(self):
print("Hello from ClassB!")
# 動態建立繼承自 ClassB 的臨時類別
TempClass = type('TempClass', (ClassB,), {
'greet': lambda self: (print("Hello from TempClass!"), super(TempClass, self).greet())[0]
})
# 創建實例並測試
temp = TempClass()
temp.greet()
type('TempClass', (ClassB,), {...})
greet
方法先印出新訊息,再透過 super()
呼叫父類別的 greet
。
Hello from TempClass!
Hello from ClassB!
To get the parameter names and their corresponding values of a function in Python, you can use the `inspect` module, which provides introspection utilities. Specifically, `inspect.signature()` can help you retrieve the names of the parameters, and you can pass the current frame's local variables to get their values. Here is an example that demonstrates how to get the function name, parameter names, and their values: ```python import inspect # Sample function def my_function(a, b, c=5): # Get the current frame frame = inspect.currentframe() # Get the function name func_name = frame.f_code.co_name print(f"Function name: {func_name}") # Get the parameter names and their values args, _, _, values = inspect.getargvalues(frame) # Print parameter names and values for arg in args: print(f"Parameter name: {arg}, Value: {values[arg]}") # Call the function my_function(1, 2) ``` ### Output: ``` Function name: my_function Parameter name: a, Value: 1 Parameter name: b, Value: 2 Parameter name: c, Value: 5 ``` ### Explanation: 1. **`inspect.currentframe()`**: Retrieves the current execution frame. 2. **`frame.f_code.co_name`**: Extracts the name of the current function. 3. **`inspect.getargvalues(frame)`**: Gets the argument names and their corresponding values from the frame. This function returns a tuple containing: - `args`: List of argument names. - `_`: Placeholder for unused information. - `values`: Dictionary containing argument names as keys and their values. This allows you to print both the names of the function's parameters and their values at runtime.
以下是使用 Python 判斷屬性屬於哪個繼承類別的範例程式碼:
import inspect
class BaseClass:
base_attr = "我是來自 BaseClass 的屬性"
class SubClass(BaseClass):
sub_attr = "我是來自 SubClass 的屬性"
# 定義函式以找出屬性歸屬的類別
def find_attribute_owner(cls, attr_name):
for base in inspect.getmro(cls): # 取得 MRO(方法解析順序)
if attr_name in base.__dict__:
return base
return None
# 測試
sub_obj = SubClass()
attributes = sub_obj.__class__.__dict__.items() # 取得類別層級的所有屬性
for name, value in attributes:
owner = find_attribute_owner(sub_obj.__class__, name)
print(f"屬性 '{name}' 屬於類別: {owner.__name__}")
__dict__
,其中儲存該類別定義的屬性。對於範例中的類別,執行結果如下:
屬性 '__module__' 屬於類別: SubClass
屬性 'sub_attr' 屬於類別: SubClass
屬性 '__doc__' 屬於類別: SubClass
屬性 'base_attr' 屬於類別: BaseClass
在 Python 中,@staticmethod
和 @classmethod
這兩個裝飾器都可以定義不需要實例化類別就能調用的方法,但它們的用途和行為有所不同。
@staticmethod
是不接受任何隱含第一個參數(無 self
或
cls
)的方法。它就像普通的函數,只是屬於類別的命名空間。@staticmethod
。class MyClass:
@staticmethod
def static_method(x, y):
return x + y
# 無需建立實例即可調用靜態方法
result = MyClass.static_method(5, 10) # 結果:15
重點:@staticmethod
無法訪問類別(cls
)或實例(self
)。
@classmethod
是接受類別本身(cls
)作為第一個參數的方法。這使得它可以訪問和修改類別的狀態。@classmethod
。class MyClass:
class_variable = 0
def __init__(self, value):
self.value = value
MyClass.class_variable += 1
@classmethod
def get_class_variable(cls):
return cls.class_variable
# 創建實例
obj1 = MyClass(10)
obj2 = MyClass(20)
# 調用類別方法
print(MyClass.get_class_variable()) # 結果:2
重點:@classmethod
可以訪問類別層級的狀態(cls
)。
特徵 | @staticmethod | @classmethod |
---|---|---|
第一個參數 | 無隱含的第一個參數 | cls (類別本身) |
訪問實例 | 無 | 無 |
訪問類別 | 無 | 有 |
用法 | 與類別相關但不需要實例或類別的工具函數 | 需要操作類別層級的數據或提供替代構造函數 |
Python 本身並沒有提供「默認靜態方法」或「默認類別方法」,即在第一次調用任何靜態或類別方法時自動執行一個方法的功能。但我們可以通過懶加載技巧來實現類似的行為。
可以在類中定義一個靜態變數來追蹤初始化的狀態,然後在第一次調用靜態或類別方法時執行初始化邏輯。
class MyClass:
initialized = False # 靜態變數,跟蹤是否已經初始化
@staticmethod
def init_once():
if not MyClass.initialized:
print("初始化邏輯執行...")
MyClass.initialized = True
@classmethod
def class_method(cls):
cls.init_once()
print("調用類別方法")
@staticmethod
def static_method():
MyClass.init_once()
print("調用靜態方法")
# 第一次調用類別方法,觸發初始化
MyClass.class_method() # 輸出: 初始化邏輯執行... 調用類別方法
# 第二次調用類別方法,不再執行初始化
MyClass.class_method() # 輸出: 調用類別方法
# 第一次調用靜態方法,不再執行初始化,因為已經初始化過
MyClass.static_method() # 輸出: 調用靜態方法
initialized
:該變數用於跟蹤類別是否已經初始化,初始值為 False
。init_once()
方法:這個方法負責執行初始化邏輯,並且在初始化後將 initialized
設為
True
,以防止重複初始化。雖然 Python 沒有內建「默認靜態方法」或「默認類別方法」,但通過使用靜態變數與懶加載技巧,你可以在第一次調用靜態或類別方法時自動執行初始化邏輯,並確保該邏輯只會被執行一次。
Pandas 是一個基於 Python 的資料分析與操作工具,專門用於處理結構化數據,例如表格數據或時間序列數據。
import pandas as pd # 建立 DataFrame data = {'姓名': ['Alice', 'Bob', 'Charlie'], '年齡': [25, 30, 35], '城市': ['台北', '台中', '高雄']} df = pd.DataFrame(data) # 查看數據 print(df) # 篩選年齡大於 28 的資料 filtered_df = df[df['年齡'] > 28] print(filtered_df)
Pandas 提供高效、靈活且直觀的操作方式,特別適合進行數據分析與處理,是數據科學和機器學習中不可或缺的工具之一。
Pandas 是一個功能強大的資料分析工具,無論是入門還是高階使用者,都能受益於其簡單易用的設計和廣泛的功能。
首先,您需要安裝 googletrans
套件。在命令列輸入以下指令:
pip install googletrans==4.0.0-rc1
注意:安裝時請確認版本是 4.0.0-rc1
,因為較舊版本可能不再適用。
以下是一個將英文翻譯成繁體中文的範例:
from googletrans import Translator
# 初始化 Translator 物件
translator = Translator()
# 翻譯文字
text = "Hello, how are you?"
result = translator.translate(text, src="en", dest="zh-tw")
# 輸出翻譯結果
print("原文:", text)
print("翻譯:", result.text)
您可以翻譯多種語言,以下是常見的語言代碼:
en
zh-tw
zh-cn
ja
ko
fr
de
Googletrans 是非官方的 Google 翻譯 API,因此有可能因為 Google 端的更改而停止運作。如果發現翻譯功能失效,請考慮使用其他翻譯 API,例如 Google 官方的 Cloud Translation API。
DeepL 提供準確性較高的翻譯服務,但需要 API key 才能使用其開發者 API。
由 Microsoft 提供的翻譯工具,支援多語言翻譯,但需使用 Azure 的 API key 設定。
Amazon Web Services (AWS) 提供的翻譯服務,針對多語言文本進行高效翻譯,需透過 AWS 提供的 API key 訪問。
LibreTranslate 是開源的翻譯工具,可自行架設服務器,不需要 API key。部分第三方公共伺服器也提供無需 API key 的使用選項。
TextBlob 是一個基於自然語言處理的工具,內建 Google Translate 的功能,但較舊版本的實現可無需 API key,可能需要注意版本支持。
MyMemory 提供基於記憶的翻譯,部分功能不需要 API key,但高級使用可能需申請。
在 Googletrans 的競爭對手中,像 LibreTranslate 和部分版本的 TextBlob 提供了無需 API key 的選擇。如果需要完全免費且無需額外設定的工具,可考慮這些選項。
以下範例將展示如何使用 Python 來查詢中文字符的所有注音。我們使用 pypinyin
套件來取得中文字的拼音,並自訂拼音轉注音符號的對應表。
pip install pypinyin
以下是 Python 程式碼,包含注音對應表及查詢並生成 HTML 結果的程式邏輯。
from pypinyin import pinyin, Style
from jinja2 import Template
# 拼音到注音的簡易對應表
pinyin_to_zhuyin = {
"a": "ㄚ", "ai": "ㄞ", "an": "ㄢ", "ang": "ㄤ", "ao": "ㄠ",
"ba": "ㄅㄚ", "bai": "ㄅㄞ", "ban": "ㄅㄢ", "bang": "ㄅㄤ", "bao": "ㄅㄠ",
# 省略部分對應,需自行完善
"hao": "ㄏㄠ", "hao": "ㄏㄠ", "hǎo": "ㄏㄠˇ", "hào": "ㄏㄠˋ"
}
# 查詢中文字符的所有拼音並轉換為注音
def get_zhuyin(char):
pinyins = pinyin(char, style=Style.NORMAL, heteronym=True)
unique_pinyins = set(pinyins[0])
zhuyins = {p: pinyin_to_zhuyin.get(p, p) for p in unique_pinyins} # 將拼音轉換為注音
return list(zhuyins.values())
# 查詢字符
chinese_char = '好' # 可更換成其他字
zhuyin_results = get_zhuyin(chinese_char)
pinyin_to_zhuyin
字典來將拼音對應為注音符號。該對應表需自行擴充。heteronym=True
確保多音字所有讀音皆會顯示出來。Python 的 logging
套件是一個強大的內建模組,用於應用程式中進行有效的日誌管理。無論是記錄調試信息、錯誤追蹤,還是性能監控,logging
套件都能提供多層級、多格式的日誌記錄方式。
DEBUG
、INFO
、WARNING
、ERROR
和 CRITICAL
。以下是一個基本的 logging
套件配置範例:
import logging
# 設定 logger
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
# 設置 Handler
console_handler = logging.StreamHandler()
file_handler = logging.FileHandler('app.log')
# 設置 Formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
# 添加 Handler 到 logger
logger.addHandler(console_handler)
logger.addHandler(file_handler)
# 測試不同級別的日誌
logger.debug('這是一條調試訊息')
logger.info('這是一條信息訊息')
logger.warning('這是一條警告訊息')
logger.error('這是一條錯誤訊息')
logger.critical('這是一條嚴重訊息')
logging
支援以下日誌級別:
DEBUG
:最低層級,用於調試資訊。INFO
:普通資訊,如系統運行狀態。WARNING
:警告資訊,但並不會導致程式停止。ERROR
:錯誤資訊,通常會因錯誤引發問題。CRITICAL
:最嚴重的錯誤,可能導致程式終止。可以使用 Formatter
類來定義日誌的輸出格式。例如:
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
這個格式會輸出類似於以下內容:
2024-10-25 10:00:00 - my_logger - INFO - 這是一條信息訊息
logging
套件提供了多樣化的日誌管理選項,讓開發者可以根據需求自訂日誌級別、輸出格式及目的地,提升應用程式的可維護性及除錯效率。
在 Python 的 logging
套件中,Handler
是一個關鍵的組件,負責定義日誌的輸出位置。不同的處理器可以將日誌輸出到不同的目標位置,包括控制台、文件、網絡、甚至是郵件。StreamHandler
是最常用的處理器之一,它負責將日誌輸出到控制台。
在 logging
中,一些常見的 Handler
包括:
StreamHandler
:將日誌輸出到 stdout
或 stderr
(通常是控制台)。FileHandler
:將日誌輸出到文件。NullHandler
:忽略日誌輸出,適用於不需要顯示的情境。SMTPHandler
:將日誌透過電子郵件發送。StreamHandler
是控制台輸出最常用的處理器,它通常會將日誌消息發送到標準錯誤(stderr
)。透過設定
StreamHandler
,可以讓日誌直接在控制台顯示,適合即時監控系統的狀態。
如果不希望日誌顯示在控制台上,可以從 Logger 中移除 StreamHandler
,或者改用 NullHandler
來避免輸出。
以下範例展示了如何配置 logging
並移除控制台輸出的 StreamHandler
:
import logging
# 設定 Logger
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
# 添加 StreamHandler 以輸出至控制台
console_handler = logging.StreamHandler()
logger.addHandler(console_handler)
# 測試輸出
logger.info("這條消息將顯示在控制台")
# 移除控制台輸出
logger.removeHandler(console_handler)
logger.info("這條消息將不會顯示在控制台")
可以使用 NullHandler
來禁用日誌的所有輸出:
import logging
# 設定 Logger 並添加 NullHandler
logger = logging.getLogger('my_logger')
logger.addHandler(logging.NullHandler())
# 這條訊息不會顯示在控制台
logger.info("這條消息將不會顯示")
Handler
是 logging
套件中定義輸出位置的組件。透過
StreamHandler
,日誌消息可以顯示在控制台,便於即時監控。若不需要控制台輸出,可以移除 StreamHandler
或使用
NullHandler
來禁用日誌輸出。
import requests # 呼叫 API url = "https://api.example.com/data" response = requests.get(url) # 確認回應成功 if response.status_code == 200: print("成功取得資料") else: print(f"錯誤:{response.status_code}")
# 解析 JSON 回應 data = response.json() # 存取 JSON 資料 print(data["key1"]) print(data["key2"]["subkey"])
import requests # API URL url = "https://jsonplaceholder.typicode.com/posts" # 發送請求 response = requests.get(url) # 檢查回應狀態並解析 if response.status_code == 200: data = response.json() # 列出每篇文章的標題 for post in data: print(f"Post ID: {post['id']}, Title: {post['title']}") else: print(f"API 呼叫失敗,狀態碼:{response.status_code}")
try: data = response.json() print(data) except ValueError: print("回應不是有效的 JSON 格式")
Python內建支援SQLite,適用於小型應用。
import sqlite3
conn = sqlite3.connect("example.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))
conn.commit()
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())
cursor.close()
conn.close()
用於連接MySQL資料庫。
pip install pymysql
import pymysql
conn = pymysql.connect(host="localhost", user="root", password="password", database="test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())
cursor.close()
conn.close()
用於連接PostgreSQL。
pip install psycopg2
import psycopg2
conn = psycopg2.connect(dbname="testdb", user="user", password="password", host="localhost")
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())
cursor.close()
conn.close()
用於連接Microsoft SQL Server。
pip install pyodbc
import pyodbc
conn = pyodbc.connect("DRIVER={SQL Server}; SERVER=localhost; DATABASE=test; UID=user; PWD=password")
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())
cursor.close()
conn.close()
適用於文件型資料庫。
pip install pymongo
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["testdb"]
collection = db["users"]
collection.insert_one({"name": "Alice", "age": 25})
print(list(collection.find()))
適用於快取與高效能Key-Value存取。
pip install redis
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
r.set("name", "Alice")
print(r.get("name"))
適用於全文搜尋與分析。
pip install elasticsearch
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
doc = {"name": "Alice", "age": 25}
es.index(index="users", document=doc)
print(es.search(index="users", query={"match_all": {}}))
支援多種SQL資料庫,提供ORM功能。
pip install sqlalchemy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, sessionmaker
engine = create_engine("sqlite:///example.db")
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
session.add(User(name="Alice"))
session.commit()
print(session.query(User).all())
sqlite3
(內建)、pymysql
(MySQL)、psycopg2
(PostgreSQL)、pyodbc
(SQL Server)。pymongo
(MongoDB)、redis
(Redis)、elasticsearch
(Elasticsearch)。SQLAlchemy
(支援多種SQL資料庫)。使用以下指令安裝PyMySQL:
pip install pymysql
使用PyMySQL連接MySQL伺服器:
import pymysql
# 建立連線
conn = pymysql.connect(
host="localhost",
user="your_user",
password="your_password",
database="your_database",
charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor # 返回字典格式
)
# 建立游標
cursor = conn.cursor()
# 查詢資料
cursor.execute("SELECT * FROM your_table")
result = cursor.fetchall()
for row in result:
print(row)
# 關閉連線
cursor.close()
conn.close()
執行INSERT、UPDATE、DELETE語句時,需要提交變更:
try:
with conn.cursor() as cursor:
sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
cursor.execute(sql, ("Alice", 25))
conn.commit() # 提交變更
except Exception as e:
conn.rollback() # 發生錯誤時回滾
print("發生錯誤:", e)
可以使用 callproc
呼叫儲存程序:
with conn.cursor() as cursor:
cursor.callproc("your_stored_procedure", (param1, param2))
result = cursor.fetchall()
print(result)
使用 executemany
進行批量插入:
data = [("Bob", 30), ("Charlie", 28), ("David", 35)]
sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
with conn.cursor() as cursor:
cursor.executemany(sql, data)
conn.commit()
使用參數化查詢來防止SQL注入攻擊:
name = "Alice"
sql = "SELECT * FROM users WHERE name = %s"
with conn.cursor() as cursor:
cursor.execute(sql, (name,))
result = cursor.fetchall()
print(result)
確保程式結束時關閉資料庫連線:
conn.close()
若要在Python中執行MySQL的儲存程序,可以使用 mysql-connector-python
或 PyMySQL
。
pip install mysql-connector-python
import mysql.connector
# 連接資料庫
conn = mysql.connector.connect(
host="localhost",
user="your_user",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
# 呼叫儲存程序
cursor.callproc("your_stored_procedure", (param1, param2))
# 取得結果
for result in cursor.stored_results():
print(result.fetchall())
# 關閉連線
cursor.close()
conn.close()
若要在Python中執行SQL Server的儲存程序,可以使用 pyodbc
。
pip install pyodbc
import pyodbc
# 連接SQL Server
conn = pyodbc.connect("DRIVER={SQL Server};"
"SERVER=your_server;"
"DATABASE=your_database;"
"UID=your_user;"
"PWD=your_password")
cursor = conn.cursor()
# 執行儲存程序
cursor.execute("{CALL your_stored_procedure (?, ?)}", (param1, param2))
# 取得結果
rows = cursor.fetchall()
for row in rows:
print(row)
# 關閉連線
cursor.close()
conn.close()
若要在Python中執行PostgreSQL的儲存程序,可以使用 psycopg2
。
pip install psycopg2
import psycopg2
# 連接PostgreSQL
conn = psycopg2.connect(
dbname="your_database",
user="your_user",
password="your_password",
host="localhost",
port="5432"
)
cursor = conn.cursor()
# 執行儲存程序
cursor.callproc("your_stored_procedure", (param1, param2))
# 取得結果
rows = cursor.fetchall()
for row in rows:
print(row)
# 關閉連線
cursor.close()
conn.close()
fetchall()
或 stored_results()
來獲取結果。這是最常見的爬蟲組合,適合初學者,用於解析靜態網頁。
pip install requests beautifulsoup4
使用範例:
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print(soup.title.string)
一個強大的爬蟲框架,適合大型爬蟲專案,支持多線程和分佈式爬蟲。
pip install scrapy
使用範例:
scrapy startproject myproject
在專案內建立爬蟲模組,運行爬取命令。
適合需要模擬使用者操作的動態網頁爬取,例如處理JavaScript渲染的內容。
pip install selenium
使用範例:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://example.com")
print(driver.title)
driver.quit()
另一個處理動態網頁的工具,相比Selenium性能更高,支持多瀏覽器。
pip install playwright
playwright install
使用範例:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://example.com")
print(page.title())
browser.close()
基於Puppeteer的Python版,專為爬取動態網頁而設計。
pip install pyppeteer
使用範例:
from pyppeteer import launch
async def main():
browser = await launch()
page = await browser.newPage()
await page.goto("https://example.com")
print(await page.title())
await browser.close()
import asyncio
asyncio.get_event_loop().run_until_complete(main())
用於發送HTTP請求的高效工具,支持異步操作。
pip install httpx
使用範例:
import httpx
async def fetch():
async with httpx.AsyncClient() as client:
response = await client.get("https://example.com")
print(response.text)
import asyncio
asyncio.run(fetch())
To create a simple web scraper in Python, you can use the requests library to get the page content, and BeautifulSoup to parse the HTML.
Here's an example of a basic web scraper:
import requests
from bs4 import BeautifulSoup
# URL to scrape
url = "https://example.com"
# Send a GET request
response = requests.get(url)
response.raise_for_status() # Check for errors
# Parse the HTML content
soup = BeautifulSoup(response.content, "html.parser")
# Extract specific data (e.g., all the headings)
headings = soup.find_all("h1")
# Print the headings
for heading in headings:
print(heading.text)
Note: You may need to install the libraries with the following commands:
pip install requests
pip install beautifulsoup4
需要提取的文字 其他文字
from bs4 import BeautifulSoup # HTML 文件 html_content = """ 需要提取的文字 其他文字 """ # 解析 HTML soup = BeautifulSoup(html_content, 'html.parser') # 查找特定標籤和類別 span_tag = soup.find('span', class_='xxxclass') # 提取文字值 if span_tag: print(span_tag.text) # 輸出:需要提取的文字 else: print("未找到匹配的標籤")
# 查找所有匹配的 標籤
span_tags = soup.find_all('span', class_='xxxclass')
# 提取每個標籤的文字
for tag in span_tags:
print(tag.text)
span_tag = soup.find('span', {'class': 'xxxclass', 'id': 'specific-id'})2. **使用正則表達式匹配類別**:
import re span_tag = soup.find('span', class_=re.compile(r'^xxx'))
Selenium 是一個開源工具,主要用於自動化網頁瀏覽器的操作。它支持多種瀏覽器,包括 Chrome、Firefox、Safari 等,並可用於測試網頁應用程式或進行網頁數據抓取。
以下是安裝 Selenium 的步驟和簡單的 Python 使用範例:
# 安裝 Selenium
pip install selenium
# 範例代碼
from selenium import webdriver
from selenium.webdriver.common.by import By
# 啟動 WebDriver
driver = webdriver.Chrome()
driver.get("https://www.example.com")
# 查找元素並執行操作
element = driver.find_element(By.TAG_NAME, "h1")
print(element.text)
# 關閉瀏覽器
driver.quit()
確保已安裝Selenium和ChromeDriver:
pip install selenium
下載並安裝適合您Chrome版本的 ChromeDriver。
Chrome的使用者資料夾包含書籤、歷史記錄、Cookie等個人資料,您可以指定使用特定的資料夾來啟動瀏覽器。
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
# 指定ChromeDriver路徑
chromedriver_path = "/path/to/chromedriver"
# 指定使用者資料夾
user_data_dir = "/path/to/your/user/data"
# 設置Chrome選項
chrome_options = Options()
chrome_options.add_argument(f"--user-data-dir={user_data_dir}")
chrome_options.add_argument("--profile-directory=Default") # 或其他子資料夾名稱
# 啟動瀏覽器
service = Service(chromedriver_path)
driver = webdriver.Chrome(service=service, options=chrome_options)
# 開啟一個網頁
driver.get("https://example.com")
# 結束程式
driver.quit()
user_data_dir
路徑是有效且可寫的目錄。chrome://version
。確保已安裝 selenium
和 psutil
:
pip install selenium psutil
以下程式碼會掃描所有運行中的 Chrome,並提取 user-data-dir
參數:
import psutil
import re
def get_all_user_data_dirs():
user_data_dirs = set()
for proc in psutil.process_iter(attrs=['pid', 'name', 'cmdline']):
try:
if proc.info['name'] and 'chrome' in proc.info['name'].lower():
cmdline = ' '.join(proc.info['cmdline'])
match = re.search(r'--user-data-dir=([^\s]+)', cmdline)
if match:
user_data_dirs.add(match.group(1))
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
return list(user_data_dirs)
print(get_all_user_data_dirs())
找到目標 user_data_dir
後,可用於 Selenium:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
chrome_user_data_dir = "C:\\Users\\YourUser\\AppData\\Local\\Google\\Chrome\\User Data"
options = Options()
options.add_argument(f"--user-data-dir={chrome_user_data_dir}")
service = Service("chromedriver.exe")
driver = webdriver.Chrome(service=service, options=options)
driver.get("https://www.google.com")
透過 psutil
解析運行中的 Chrome 進程,即可獲取所有 user-data-dir
,並在 Selenium 中使用特定的 user_data_dir
啟動瀏覽器。
若要從 Chrome 使用者資料目錄中獲取使用者名稱,您需要訪問該目錄中的檔案,通常是位於以下路徑:
C:\Users\[Username]\AppData\Local\Google\Chrome\User Data\
(Windows)/Users/[Username]/Library/Application Support/Google/Chrome/
(macOS)/home/[Username]/.config/google-chrome/
(Linux)這些資料夾包含許多檔案,您可以讀取 Local State
檔案來獲取使用者的基本資訊。
Local State
檔案Chrome 的 Local State
檔案包含一些基本的使用者設定,您可以從中取得使用者的資料。
import json
import os
def get_chrome_user_name(user_data_dir):
local_state_path = os.path.join(user_data_dir, 'Local State')
# 檢查檔案是否存在
if not os.path.exists(local_state_path):
return "Local State file not found"
with open(local_state_path, 'r', encoding='utf-8') as file:
local_state = json.load(file)
# 從 Local State 取得使用者資訊
user_name = local_state.get('profile', {}).get('name', 'Unknown User')
return user_name
# 示例:Chrome 使用者資料目錄路徑
user_data_dir = r'C:\Users\YourUserName\AppData\Local\Google\Chrome\User Data'
print(get_chrome_user_name(user_data_dir))
當您讀取 Local State
檔案並將其解析為 JSON 時,可以從中取得許多資料,例如:
profile
:包含使用者的配置資料,如名稱、圖片等。last_version
:顯示上次的 Chrome 版本。is_logged_in
:顯示使用者是否登入。在大多數情況下,使用者名稱將位於 profile
下,並可通過上述方法提取。
通過解析 Local State
檔案中的 JSON 資料,您可以輕鬆地獲取 Chrome 使用者的名稱。
Chrome 的 Local State
檔案存儲了許多使用者的基本資料。若您想從中提取所有使用者名稱,可以讀取該檔案並解析其 JSON 內容。以下是如何實現這一目標的步驟。
Local State
檔案並解析您可以讀取位於 Chrome 使用者資料目錄中的 Local State
檔案,然後解析其中的 JSON 格式內容來提取所有使用者的資料。
import json
import os
def get_all_users(user_data_dir):
local_state_path = os.path.join(user_data_dir, 'Local State')
# 檢查檔案是否存在
if not os.path.exists(local_state_path):
return "Local State file not found"
with open(local_state_path, 'r', encoding='utf-8') as file:
local_state = json.load(file)
# 從 Local State 取得所有使用者資料
profiles = local_state.get('profile', {}).get('info_cache', {})
# 獲取所有使用者名稱
user_names = [profile.get('name', 'Unknown User') for profile in profiles.values()]
return user_names
# 示例:Chrome 使用者資料目錄路徑
user_data_dir = r'C:\Users\YourUserName\AppData\Local\Google\Chrome\User Data'
print(get_all_users(user_data_dir))
在 Chrome 的 Local State
檔案中,使用者資料通常儲存在 profile
下的 info_cache
中,這是一個字典,其中每個使用者的資料都是以其配置名稱為鍵。
Local State
檔案結構以下是 Local State
檔案中的結構範例:
{
"profile": {
"info_cache": {
"profile1": {
"name": "User1",
"avatar": "path/to/avatar1.jpg"
},
"profile2": {
"name": "User2",
"avatar": "path/to/avatar2.jpg"
}
}
}
}
通過解析 Local State
檔案,您可以獲取 Chrome 中所有使用者的名稱。這使得可以輕鬆地列出所有帳戶。
在 Chrome 的 Local State
檔案中,每個使用者的資料都包含在 info_cache
中。您可以從中提取使用者名稱以及對應的配置子目錄。
Local State
檔案並解析以下是如何從 Chrome 的 Local State
檔案中獲取所有使用者的名稱和對應的子目錄的方法。
import json
import os
def get_users_and_profiles(user_data_dir):
local_state_path = os.path.join(user_data_dir, 'Local State')
# 檢查檔案是否存在
if not os.path.exists(local_state_path):
return "Local State file not found"
with open(local_state_path, 'r', encoding='utf-8') as file:
local_state = json.load(file)
# 從 Local State 取得所有使用者資料
profiles = local_state.get('profile', {}).get('info_cache', {})
# 獲取所有使用者名稱及其對應的子目錄
user_info = {}
for profile_key, profile_data in profiles.items():
user_name = profile_data.get('name', 'Unknown User')
profile_sub_dir = os.path.join(user_data_dir, 'Profile ' + profile_key)
user_info[user_name] = profile_sub_dir
return user_info
# 示例:Chrome 使用者資料目錄路徑
user_data_dir = r'C:\Users\YourUserName\AppData\Local\Google\Chrome\User Data'
users_and_profiles = get_users_and_profiles(user_data_dir)
for user_name, profile_dir in users_and_profiles.items():
print(f"使用者名稱: {user_name}, 子目錄: {profile_dir}")
在 Local State
檔案中,所有使用者的資料都位於 profile
下的 info_cache
。每個使用者有一個對應的配置鍵(例如 profile1
, profile2
等)。每個配置的資料中包含使用者的名稱(name
)和其他相關資料。
Local State
檔案結構以下是 Local State
檔案中的結構範例:
{
"profile": {
"info_cache": {
"Profile 1": {
"name": "User1",
"avatar": "path/to/avatar1.jpg"
},
"Profile 2": {
"name": "User2",
"avatar": "path/to/avatar2.jpg"
}
}
}
}
Profile
開頭,後面跟著數字(如 Profile 1
, Profile 2
等)。通過解析 Local State
檔案,您可以獲取所有使用者的名稱及其對應的配置子目錄。這使得您可以輕鬆地找到每個使用者的配置資料位置。
若要從 Chrome 使用者資料目錄中獲取 Gmail 帳號,您需要從 Chrome 配置資料中提取相關資訊。這通常可以通過解析 Chrome 的使用者資料檔案來實現,特別是 Google 相關的帳戶資料。
每個 Chrome 使用者的資料會存在於各自的資料夾中,通常在 User Data
目錄下的 Profile
目錄內。若該使用者已登入 Google 帳號,則可以在配置資料中找到相關的 Gmail 帳號資料。
import os
import json
def get_gmail_from_profile(user_data_dir, profile_name):
profile_dir = os.path.join(user_data_dir, profile_name)
accounts_file = os.path.join(profile_dir, 'Web Data')
# 檢查檔案是否存在
if not os.path.exists(accounts_file):
return "Web Data file not found"
# 嘗試讀取 Web Data 檔案
try:
with open(accounts_file, 'r', encoding='utf-8') as file:
web_data = json.load(file)
# 從資料中提取 Gmail 賬號
for row in web_data.get('accounts', []):
if 'gmail' in row.get('email', ''):
return row.get('email')
return "No Gmail account found"
except Exception as e:
return f"Error reading Web Data file: {e}"
# 示例:Chrome 使用者資料目錄路徑
user_data_dir = r'C:\Users\YourUserName\AppData\Local\Google\Chrome\User Data'
# 假設使用的是 Profile 1
profile_name = 'Profile 1'
print(get_gmail_from_profile(user_data_dir, profile_name))
Web Data 檔案包含了 Chrome 中的多種登入資料,包括帳號的名稱、密碼和其他相關資訊。在此例中,我們尋找其中的 email
欄位,並檢查是否包含 Gmail 的郵箱。
以下是 Web Data 檔案的一部分結構範例:
{
"accounts": [
{
"email": "[email protected]",
"password": "encrypted_password_1"
},
{
"email": "[email protected]",
"password": "encrypted_password_2"
}
]
}
email
)通常可以被提取。通過解析 Chrome 使用者資料中的 Web Data
檔案,您可以輕鬆地獲取使用者的 Gmail 帳號。如果該使用者已經登入 Gmail 帳號,則相應的電子郵件會顯示在資料中。
常見的網頁自動化工具包括 Selenium 和 Playwright。這些工具可以模擬點擊、輸入文字以及其他使用者操作。
使用工具如 BeautifulSoup 或 Playwright,獲取網站上的所有超連結 (<a href>
),以此來建立需要瀏覽的頁面列表。
透過 Selenium 或 Playwright 開啟瀏覽器並模擬使用者的行為,例如點擊按鈕、滾動頁面,甚至觸發動態內容。
現代網站通常包含大量動態生成的內容,可以使用 Playwright 或 Selenium 來執行 JavaScript,確保正確加載頁面。
根據抓取到的連結,遞迴地訪問網站中的所有頁面,並記錄已經訪問的頁面以避免重複。
在瀏覽每個頁面時,模擬常見的使用者行為,例如填寫表單、提交資料,並將操作的結果記錄下來。
from selenium import webdriver from selenium.webdriver.common.by import By # 初始化瀏覽器 driver = webdriver.Chrome() # 開始瀏覽網站 driver.get("https://example.com") # 抓取所有連結 links = driver.find_elements(By.TAG_NAME, "a") for link in links: href = link.get_attribute("href") print(f"發現連結: {href}") # 模擬點擊 if links: links[0].click() # 關閉瀏覽器 driver.quit()
在進行網站瀏覽和模擬操作時,請遵守相關網站的使用條款,避免造成過多的伺服器負擔或違反法律。
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 初始化 WebDriver driver = webdriver.Chrome() # 打開目標網站 driver.get("https://example.com") # 等待按鈕出現並點擊 wait = WebDriverWait(driver, 10) button = wait.until(EC.element_to_be_clickable((By.ID, "button_id"))) button.click() # 等待其他元素加載 text_field = wait.until(EC.visibility_of_element_located((By.NAME, "text_field_name"))) text_field.send_keys("測試數據") # 關閉瀏覽器 driver.quit()
import time from selenium import webdriver # 初始化 WebDriver driver = webdriver.Chrome() # 打開目標網站 driver.get("https://example.com") time.sleep(3) # 暫停 3 秒 # 模擬按鈕點擊 button = driver.find_element(By.ID, "button_id") button.click() time.sleep(3) # 關閉瀏覽器 driver.quit()**注意**:`time.sleep` 不建議用於正式測試,僅適用於調試過程。
from selenium import webdriver # 初始化 WebDriver driver = webdriver.Chrome() # 打開目標網站 driver.get("https://example.com") # 手動確認後繼續 input("按 Enter 繼續下一步...") button = driver.find_element(By.ID, "button_id") button.click() # 繼續執行其他測試 input("按 Enter 繼續下一步...") driver.quit()
import unittest from selenium import webdriver class TestExample(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() def test_step_by_step(self): driver = self.driver driver.get("https://example.com") input("檢查頁面,按 Enter 繼續...") # 手動斷點 button = driver.find_element(By.ID, "button_id") button.click() input("檢查操作結果,按 Enter 繼續...") # 手動斷點 def tearDown(self): self.driver.quit() if __name__ == "__main__": unittest.main()
from selenium import webdriver
from selenium.webdriver.common.by import By
# 初始化 Selenium
driver = webdriver.Chrome()
driver.get("你的目標網頁 URL")
# 搜尋特定行開頭文字
target_text = "目標開頭文字"
rows = driver.find_elements(By.CSS_SELECTOR, "table tr")
# 儲存結果
result_data = []
for row in rows:
cells = row.find_elements(By.TAG_NAME, "td")
if cells and cells[0].text.startswith(target_text):
# 獲取同行後面的資料
result_data.append([cell.text for cell in cells])
driver.quit()
# 將結果轉換成 HTML
html_output = "<h2>搜尋結果</h2>\n"
for i, row_data in enumerate(result_data, start=1):
html_output += f"<h3>第 {i} 行</h3>\n<ul>\n"
for data in row_data:
html_output += f" <li>{data}</li>\n"
html_output += "</ul>\n"
# 顯示結果
print(html_output)
搜尋結果
第 1 行
- 目標開頭文字1
- 其他資料1
- 其他資料2
第 2 行
- 目標開頭文字2
- 其他資料1
- 其他資料2
startswith
方法判斷文字是否符合條件。<h2>
和 <h3>
,並以無序列表 <ul>
組織資料。<head>
與 <body>
:僅生成必要的 HTML 標籤,方便嵌入其他頁面。在 Selenium 中,find_elements(By.XPATH, xpath)
用於根據 XPath 選擇器查找符合條件的所有元素,並返回一個列表。它與 find_element(By.XPATH, xpath)
不同,後者只返回第一個匹配的元素。
from selenium import webdriver
from selenium.webdriver.common.by import By
# 啟動瀏覽器
driver = webdriver.Chrome()
# 打開網頁
driver.get("https://example.com")
# 使用 XPath 查找所有符合條件的元素
elements = driver.find_elements(By.XPATH, "//div[@class='example-class']")
# 遍歷找到的元素並輸出內容
for element in elements:
print(element.text)
# 關閉瀏覽器
driver.quit()
XPath 表達式 | 描述 |
---|---|
//tagname |
選擇所有指定標籤的元素,如 //div 代表所有 div 元素 |
//tagname[@attribute='value'] |
根據屬性值選擇元素,例如 //input[@type='text'] |
//tagname[contains(@attribute, 'value')] |
包含某些文字的屬性,如 //div[contains(@class, 'header')] |
//tagname[text()='text'] |
選擇完全匹配文字的元素,如 //button[text()='提交'] |
//tagname[contains(text(), 'text')] |
選擇包含特定文字的元素,如 //p[contains(text(), '歡迎')] |
//*[@id='some-id'] |
選擇具有特定 ID 的元素 |
(//tagname)[index] |
選擇第 index 個匹配的元素,例如 (//div)[1] 選擇第一個 div |
假設有以下 HTML 結構:
<div class="product">商品 A</div>
<div class="product">商品 B</div>
<div class="product">商品 C</div>
我們可以使用以下 Selenium 代碼獲取所有 product
類別的 div
元素:
elements = driver.find_elements(By.XPATH, "//div[@class='product']")
for element in elements:
print(element.text)
find_elements()
返回的是一個列表,即使只找到一個元素也會返回列表。find_element()
,否則 find_elements()
。find_elements(By.XPATH, xpath)
是 Selenium 中強大且靈活的查找方法,可用於定位網頁上的多個元素,並適用於爬蟲和自動化測試。
在 Selenium 中,By.LINK_TEXT
和 By.PARTIAL_LINK_TEXT
用於根據超連結的文字內容來查找元素:
By.LINK_TEXT
:根據完整的連結文字精確匹配。By.PARTIAL_LINK_TEXT
:根據部分連結文字進行模糊匹配。from selenium import webdriver
from selenium.webdriver.common.by import By
# 啟動瀏覽器
driver = webdriver.Chrome()
# 打開網頁
driver.get("https://example.com")
# 使用 LINK_TEXT 查找超連結
element = driver.find_element(By.LINK_TEXT, "完整連結文字")
print(element.get_attribute("href"))
# 使用 PARTIAL_LINK_TEXT 查找超連結
element_partial = driver.find_element(By.PARTIAL_LINK_TEXT, "部分文字")
print(element_partial.get_attribute("href"))
# 關閉瀏覽器
driver.quit()
<a href="https://example.com/page1">完整連結文字</a>
<a href="https://example.com/page2">點擊這裡了解更多</a>
假設要點擊 <a>完整連結文字</a>
,可以使用:
driver.find_element(By.LINK_TEXT, "完整連結文字").click()
如果超連結是「點擊這裡了解更多」,但我們只知道「點擊這裡」,可以使用:
driver.find_element(By.PARTIAL_LINK_TEXT, "點擊這裡").click()
By.PARTIAL_LINK_TEXT
。By.LINK_TEXT
來精確匹配。<a>
標籤的連結。find_elements()
會返回一個列表,而 find_element()
只返回第一個匹配的元素。By.LINK_TEXT
適用於精確查找完整連結,而 By.PARTIAL_LINK_TEXT
更靈活,可用於匹配部分連結文字。
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
driver = webdriver.Chrome()
driver.get("URL")
alert = Alert(driver)
print(alert.text) # 取得警示訊息
alert.accept() # 點擊確定
driver.quit()
alert = Alert(driver)
print(alert.text)
alert.accept() # 點擊確定
# alert.dismiss() # 點擊取消
alert = Alert(driver)
print(alert.text)
alert.send_keys("測試輸入") # 輸入內容
alert.accept() # 點擊確定
driver.switch_to.alert
切換到警示框。try-except
處理異常,以避免測試失敗。
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
WebDriverWait(driver, 10).until(EC.alert_is_present())
在 Selenium 中,可以使用 WebDriverWait
來檢查警示框是否存在,避免因為警示框未出現而導致錯誤。
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("URL")
try:
# 等待 5 秒檢查是否有警示框
WebDriverWait(driver, 5).until(EC.alert_is_present())
alert = Alert(driver)
print("警示框內容:", alert.text)
alert.accept() # 點擊確定
except:
print("沒有發現警示框")
driver.quit()
WebDriverWait
確保警示框出現後才切換,避免 NoAlertPresentException
。try-except
來防止因為沒有警示框而導致測試失敗。使用 WebDriverWait(driver, 5).until(EC.alert_is_present())
只能檢測 JavaScript 產生的警示框,而無法檢測 Chrome 系統級別的警示框,例如「儲存密碼」、「網站通知」等。
ChromeOptions
禁用系統級別警示框。pyautogui
或 Win32 API
來模擬鍵盤或滑鼠操作。可以在啟動 Chrome 時,透過 ChromeOptions
來關閉通知和其他系統級彈出視窗。
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--disable-notifications") # 禁用通知
options.add_argument("--disable-save-password-bubble") # 禁用儲存密碼提示
driver = webdriver.Chrome(options=options)
driver.get("URL")
若警示框已出現,可以使用 pyautogui
來模擬按鍵操作,例如按 Enter
或 Esc
來關閉。
import pyautogui
import time
time.sleep(3) # 等待警示框出現
pyautogui.press("enter") # 模擬按下 Enter 鍵
若在 Windows 環境,可以使用 pygetwindow
和 pywinauto
來偵測並關閉系統級彈出視窗。
import pygetwindow as gw
import pywinauto
windows = gw.getWindowsWithTitle("Google Chrome") # 獲取 Chrome 視窗
for win in windows:
if "system alert" in win.title.lower(): # 檢查標題是否包含 "system alert"
win.close() # 關閉視窗
ChromeOptions
來預防警示框。pyautogui
或 Win32 API
來模擬鍵盤或視窗操作。要從 Thunderbird 提取電子郵件,可以使用 Python 的 IMAP 協議庫,例如 imaplib
或第三方庫 imapclient
。首先,請確保
Thunderbird 已啟用 IMAP 協議並允許外部應用程式連接。
使用 pip 安裝相關庫:
pip install imapclient pyzmail36
使用以下代碼連接到電子郵件伺服器並提取重要電子郵件:
import imapclient
from pyzmail import PyzMessage
# 設定郵件伺服器和登入資訊
IMAP_SERVER = 'imap.example.com' # 替換為您的 IMAP 伺服器地址
EMAIL = '[email protected]'
PASSWORD = 'your_password'
# 連接到 IMAP 伺服器
with imapclient.IMAPClient(IMAP_SERVER) as client:
client.login(EMAIL, PASSWORD)
client.select_folder('INBOX')
# 搜尋標示為重要的郵件
messages = client.search(['FLAGGED'])
for uid in messages:
raw_message = client.fetch([uid], ['BODY[]'])[uid][b'BODY[]']
message = PyzMessage.factory(raw_message)
# 顯示郵件資訊
print(f"Subject: {message.get_subject()}")
print(f"From: {message.get_address('from')}")
print(f"Date: {message.get_decoded_header('date')}")
執行上述代碼,查看是否能成功提取標示為重要的電子郵件。如果有任何連接問題,可以檢查伺服器設置,或者在 IMAP 協議層進行更詳細的調試。
這樣,您可以成功使用 Python 從 Thunderbird 提取重要電子郵件。
使用以下指令安裝PyAutoGUI:
pip install pyautogui
PyAutoGUI 是一個自動化工具,允許模擬滑鼠、鍵盤操作,適合GUI自動化測試或重複性工作。
控制滑鼠的位置和操作:
import pyautogui
# 取得螢幕解析度
screen_width, screen_height = pyautogui.size()
print(f"螢幕解析度: {screen_width}x{screen_height}")
# 移動滑鼠到指定座標
pyautogui.moveTo(100, 100, duration=1)
# 從當前位置移動滑鼠
pyautogui.move(50, 50, duration=1)
# 模擬滑鼠點擊
pyautogui.click(200, 200)
# 模擬滑鼠右鍵
pyautogui.rightClick()
# 模擬拖曳操作
pyautogui.dragTo(400, 400, duration=1)
模擬鍵盤按鍵輸入:
import pyautogui
# 輸入文字
pyautogui.write("Hello, PyAutoGUI!", interval=0.1)
# 模擬按下特定按鍵
pyautogui.press("enter")
# 同時按下多個按鍵
pyautogui.hotkey("ctrl", "c") # 複製文字
擷取螢幕截圖或尋找特定影像:
import pyautogui
# 擷取整個螢幕
screenshot = pyautogui.screenshot()
screenshot.save("screenshot.png")
# 在螢幕中尋找影像
location = pyautogui.locateOnScreen("image.png")
if location:
print(f"影像位置: {location}")
else:
print("影像未找到")
防止程式無限執行,可以使用 pyautogui.FAILSAFE
:
pyautogui.FAILSAFE = True # 預設為True
# 將滑鼠移到螢幕左上角 (0, 0) 可立即停止程式
如果 Surfshark VPN 沒有提供命令列工具(如 surfshark-cli
),則需要透過 GUI 自動化工具(如 pyautogui
)模擬人工操作。
pyautogui
模組(可透過 pip install pyautogui
安裝)。透過 pyautogui
自動化點擊 Surfshark 的圖形介面按鈕來連接或斷開 VPN。
以下範例假設 Surfshark VPN 的按鈕位置固定,並使用 pyautogui
進行操作:
import pyautogui
import time
def connect_vpn():
# 確保 Surfshark 已開啟
print("嘗試連接 VPN...")
# 模擬點擊「連接」按鈕,根據實際位置調整座標
pyautogui.click(x=500, y=300) # 替換成「連接」按鈕的位置
time.sleep(5) # 等待連接完成
print("VPN 已連接")
def disconnect_vpn():
# 確保 Surfshark 已開啟
print("嘗試斷開 VPN...")
# 模擬點擊「斷開」按鈕,根據實際位置調整座標
pyautogui.click(x=500, y=350) # 替換成「斷開」按鈕的位置
time.sleep(5) # 等待斷開完成
print("VPN 已斷開")
# 測試
connect_vpn()
disconnect_vpn()
x
和 y
的座標。subprocess
打開應用程式,例如
subprocess.run("start surfshark.exe", shell=True)
。如果座標方式不穩定,可以使用影像識別(如 pyautogui.locateOnScreen()
)來找到按鈕位置,增加靈活性。
Kivy 是一個開源的 Python 框架,用來快速開發多點觸控應用程序。它的設計初衷是跨平台支持,允許開發者在 Windows、macOS、Linux、iOS 和 Android 等多個平台上運行同一份代碼。Kivy 特別適合構建用於手機、平板電腦和桌面設備的 GUI 應用程序,並且它有良好的多點觸控支持。
Kivy 的應用程序由多個 Widget 組成,這些 Widget 可以通過代碼或 Kivy 的專用語言 KV 文件進行布局。以下是一個簡單的應用程序範例,它顯示了一個按鈕,當按鈕被點擊時會改變顏色。
from kivy.app import App
from kivy.uix.button import Button
class MyApp(App):
def build(self):
return Button(text='Hello, Kivy!',
background_color=(0, 1, 0, 1)) # 綠色按鈕
if __name__ == '__main__':
MyApp().run()
可以通過 pip 安裝 Kivy:
pip install kivy
Kivy 適用於多種應用場景,包括但不限於:
Kivy 是一個用於建立跨平台應用的 Python 框架,但它通常運行在本地裝置上。要將 Kivy 應用程式顯示在遠端,您可以考慮以下幾種方式:
您可以使用 VNC(Virtual Network Computing)或其他遠端桌面工具(如 RDP、TeamViewer 等)來遠端控制並顯示 Kivy 應用程式。
對於使用 Linux 的用戶,您可以使用 X11 forwarding 在遠端顯示圖形界面:
ssh -X username@remote_host
您可以使用 Flask 或其他 Web 框架將 Kivy 應用程式部分功能暴露給遠端用戶,並使用 Web 瀏覽器顯示:
如果您希望在容器化環境中運行 Kivy 應用,您可以使用 Docker 和 VNC 進行設置:
This error indicates that the tickmarker module from Kivy's Garden is not installed. To fix this issue, follow the steps below:
pip install kivy-garden
garden install tickmarker
Once you've done these steps, try running your Kivy application again.
Gradio 是一個開源的 Python 庫,旨在讓機器學習模型變得更加可訪問和易於互動。通過簡單的代碼,您可以快速為您的機器學習模型建立一個網頁界面,供他人測試和使用。
Gradio 的用法非常簡單,以下是一個基本的範例,顯示如何創建一個簡單的文字輸入和輸出的介面:
import gradio as gr
# 定義處理輸入數據的函數
def greet(name):
return "你好," + name + "!"
# 創建 Gradio 介面
iface = gr.Interface(fn=greet, inputs="text", outputs="text")
# 啟動介面
iface.launch()
上面的程式碼將創建一個簡單的網頁介面,讓使用者可以輸入名字,然後顯示個人化的問候語。
Gradio 為開發者提供了一個簡單且強大的工具,能夠快速將機器學習模型轉化為網頁應用,讓更廣泛的使用者能夠輕鬆地測試和體驗 AI 的成果。無論是用於個人項目還是團隊合作,Gradio 都是推廣和展示模型的理想選擇。
如果想將 Gradio 介面的輸出重定向到 Apache HTTP 伺服器的頁面(如 `/results`),您可以使用 Python 的 requests
模組來將 Gradio
的結果傳送到伺服器。以下是如何將 Gradio 和 Apache 整合的基本步驟:
首先,確保您的 Apache HTTP 伺服器正在運行,並且已經配置好一個能夠處理數據的端點(例如 /results
)。這個端點可以是 PHP、Python 或其他後端語言來處理傳入的數據。
以下是如何編寫 Gradio 應用程式並將其輸出結果重定向到 HTTP 伺服器的範例代碼:
import gradio as gr
import requests
# 處理 Gradio 輸入並重定向到 HTTP 伺服器
def process_and_redirect(input_data):
# 對輸入數據進行處理
result = f"Processed: {input_data}"
# 向 Apache HTTP 伺服器發送 HTTP POST 請求,並攜帶處理後的數據
url = 'http://your-apache-server-address/results' # 替換為您的伺服器地址
payload = {'result': result}
try:
response = requests.post(url, data=payload)
if response.status_code == 200:
return f"成功重定向到 {url}。"
else:
return f"重定向失敗。狀態碼: {response.status_code}"
except Exception as e:
return f"發生錯誤: {str(e)}"
# 創建 Gradio 介面
iface = gr.Interface(
fn=process_and_redirect,
inputs="text",
outputs="text",
title="Gradio 重定向到 HTTP 伺服器"
)
iface.launch()
您的 Apache 伺服器應該配置好處理 POST 請求的端點,例如一個簡單的 PHP 腳本來接收 Gradio 的數據:
<?php
// 處理來自 Gradio 的 POST 請求
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$result = $_POST['result']; // 從 POST 請求中獲取 'result' 參數
echo "從 Gradio 接收到的數據: " . htmlspecialchars($result);
}
?>
這樣,您可以使用 Gradio 應用程式將輸出重定向到 Apache HTTP 伺服器,並在伺服器端處理數據。這樣的整合使得 Gradio 的互動功能能夠更廣泛地應用於 Web 環境中。
在 Apache 頁面中嵌入 Gradio 介面最簡單的方式是使用 iframe
標籤。設定 src
屬性為 Gradio 伺服器的 URL。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Apache 介面嵌入 Gradio</title>
</head>
<body>
<h1>嵌入 Gradio 介面</h1>
<iframe src="http://your-gradio-server-address:7860" width="100%" height="800px" frameborder="0"></iframe>
</body>
</html>
如果希望透過 Apache 的 URL 直接訪問 Gradio 介面,可以配置反向代理。這樣無需顯示原始的 Gradio URL。
mod_proxy
和 mod_proxy_http
模組。執行以下指令:sudo a2enmod proxy
sudo a2enmod proxy_http
或是un-comment:
#LoadModule proxy_module modules/mod_proxy.so
#LoadModule proxy_http_module modules/mod_proxy_http.so
/gradio
)。<Location "/gradio">
ProxyPass "http://localhost:7860/"
ProxyPassReverse "http://localhost:7860/"
</Location>
sudo systemctl restart apache2
完成後,您可以透過 http://your-apache-server-address/gradio
在 Apache 頁面中顯示來自 Gradio 的介面內容。
在 Apache 中,確保已啟用 proxy
和 proxy_http
模組。若尚未啟用,可以執行以下指令:
sudo a2enmod proxy
sudo a2enmod proxy_http
在 Gradio 應用的 Apache 配置檔案中 (例如 /etc/apache2/sites-available/yourdomain.conf
),新增以下設定來配置 ProxyPass
和 ProxyPassReverse:
<VirtualHost *:80>
ServerName yourdomain.com
# 將 Gradio 根目錄指向 Gradio 伺服器
ProxyPass / http://localhost:7860/
ProxyPassReverse / http://localhost:7860/
# 確保靜態資源能被正常代理
ProxyPass /static/ http://localhost:7860/static/
ProxyPassReverse /static/ http://localhost:7860/static/
</VirtualHost>
完成設定後,請重啟 Apache 以套用更改:
sudo systemctl restart apache2
這樣的配置可以明確處理對 Gradio 靜態資源 (如 theme.css
) 的請求,應能解決缺少樣式的問題。如果 Gradio 的靜態檔案路徑非
/static/
,請根據實際情況調整路徑。
在 Gradio 中可以使用 gr.DataFrame
元件來顯示或編輯表格數據,例如顯示 Pandas DataFrame 或其他表格格式的數據。在這裡,我們將介紹如何在 Gradio
應用中使用 DataFrame 元件來創建交互式的數據表格。
如果尚未安裝 Gradio,可以使用以下命令安裝:
pip install gradio
gr.DataFrame
顯示表格數據以下是如何使用 Gradio 來展示 DataFrame。假設我們有一個 Pandas DataFrame,需要在 Gradio 應用中顯示:
import gradio as gr
import pandas as pd
# 創建示例 DataFrame
data = {'名稱': ['Alice', 'Bob', 'Charlie'], '年齡': [25, 30, 35], '職業': ['工程師', '設計師', '醫生']}
df = pd.DataFrame(data)
# 定義函數以返回 DataFrame
def show_dataframe():
return df
# 創建 Gradio 界面
interface = gr.Interface(fn=show_dataframe, outputs=gr.DataFrame(), title="人員數據表")
interface.launch()
import gradio as gr
:引入 Gradio 套件。data
:用於創建示例數據的字典,包含姓名、年齡和職業三欄。show_dataframe
:定義函數以返回 Pandas DataFrame 以供顯示。gr.DataFrame()
:創建 DataFrame 元件,用於 Gradio 界面中的表格顯示。interface.launch()
:啟動 Gradio 應用。gr.DataFrame
進行互動編輯如果希望讓使用者能夠編輯表格,可以在 gr.DataFrame
中設置 editable=True
,允許使用者修改表格數據:
interface = gr.Interface(fn=show_dataframe, outputs=gr.DataFrame(editable=True), title="可編輯的人員數據表")
啟動後的應用會顯示可編輯的表格,使用者可以直接在網頁上對數據進行修改。
可以使用 psutil
模組來查找 Gradio 程序的 PID。首先,確保已安裝 psutil
:
pip install psutil
接著可以用以下程式碼找到 Gradio 相關程序的 PID。
import psutil
# 搜索包含 'gradio' 的程序
for process in psutil.process_iter(['pid', 'name', 'cmdline']):
if 'gradio' in ' '.join(process.info['cmdline']):
print("找到 Gradio 程序 PID:", process.info['pid'])
找到 PID 後,可以使用 terminate()
或 kill()
方法來終止該程序。例如:
for process in psutil.process_iter(['pid', 'name', 'cmdline']):
if 'gradio' in ' '.join(process.info['cmdline']):
process.kill() # 強制終止程序
print(f"已終止 Gradio 程序 PID: {process.info['pid']}")
使用 kill()
方法會立即終止程序,因此請確保該程序無正在進行的重要操作。此範例程式碼會終止所有匹配到的 Gradio 程序。
可以使用 psutil
模組來查找監聽特定埠的程序。首先,確保已安裝 psutil
:
pip install psutil
接著,可以用以下程式碼查找監聽 7860
埠的程序 PID。
import psutil
# 指定要查找的埠號
target_port = 7860
pid_to_kill = None
# 搜索監聽指定埠的程序
for conn in psutil.net_connections(kind='inet'):
if conn.laddr.port == target_port and conn.status == psutil.CONN_LISTEN:
pid_to_kill = conn.pid
break
if pid_to_kill:
print("找到監聽埠 7860 的程序 PID:", pid_to_kill)
else:
print("未找到監聽埠 7860 的程序")
找到 PID 後,可以使用 psutil.Process
的 kill()
方法來強制終止程序:
if pid_to_kill:
process = psutil.Process(pid_to_kill)
process.kill() # 強制終止程序
print(f"已終止監聽埠 7860 的程序 PID: {pid_to_kill}")
else:
print("無法終止程序,因為未找到該 PID")
此程式碼將強制終止任何監聽指定埠的程序。請確認該埠確實為 Gradio 使用,以免誤終止其他服務。
Manim(Mathematical Animation Engine)是一個用 Python 編寫的動畫庫,特別用來創建數學圖像和動畫。Manim 可以用於生成高品質的動畫,展示數學概念、代碼運行過程,或者任何以圖像和動畫表現的東西。
Manim 的動畫一般是通過編寫 Python 腳本來完成的,然後生成視頻文件。每個動畫通常包含一個或多個場景 (Scene),而每個場景則由不同的對象 (Mobject) 組成。
from manim import *
class MyFirstScene(Scene):
def construct(self):
text = Text("Hello, Manim!") # 創建一個文字對象
self.play(Write(text)) # 生成動畫
可以通過 pip 安裝 Manim:
pip install manim
ManimGL 是 Manim 的一個高效變體,用於製作數學動畫,專注於 OpenGL 加速來提高渲染速度。
使用 pip 安裝:
pip install manimgl
或從 GitHub 獲取最新版本:
git clone https://github.com/ManimCommunity/ManimGL.git
cd ManimGL
pip install -e .
使用 ManimGL 渲染一個簡單場景:
from manimlib import *
class HelloManim(Scene):
def construct(self):
text = Text("Hello, ManimGL!")
self.play(Write(text))
self.wait(2)
運行指令:
manimgl script.py HelloManim
如果遇到安裝或運行問題,可嘗試:
pip install --upgrade pip
bpy
模組是一個專門為 Blender 設計的 Python API,允許使用者在 Blender 內透過程式碼來創建、修改以及管理 3D 圖像和動畫。
bpy
?bpy
是 Blender Python 的縮寫,它是一組函數庫,允許使用 Python 腳本來操作 Blender 的核心功能。透過 bpy
,使用者可以:
bpy
的主要模組和功能bpy
包含了多個子模組,每個模組都有特定的用途:
bpy.data
: 存取 Blender 中的所有數據(如物件、材質、場景等)。bpy.ops
: 操作類,執行操作(如移動、旋轉、縮放物件)。bpy.context
: 訪問目前的 Blender 狀態(如選中的物件或啟用的工具)。bpy.types
: 定義 Blender 中所有的數據結構(如 Mesh、Camera、Material)。bpy.utils
: 提供一些輔助功能(如腳本加載和卸載)。以下是使用 bpy
創建立方體的簡單範例:
import bpy
# 刪除現有物件
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# 添加立方體
bpy.ops.mesh.primitive_cube_add(size=2, enter_editmode=False, align='WORLD', location=(0, 0, 0))
bpy
?使用 bpy
讓你可以將重複的工作自動化,並且生成複雜的模型、動畫和渲染。對於遊戲設計師、建築師、動畫師等專業人士來說,bpy
提供了強大的工具來優化工作流程。
欲了解更多關於 bpy
模組的細節,請參考官方文件:Blender Python API Documentation
email: [email protected]