Python



Python常用連結

  • Python官方

    Python 的優勢

    簡潔易學的語法

    Python 的語法簡單且接近自然語言,即使是程式設計新手也能快速上手,降低了學習的門檻。

    豐富的標準庫與第三方資源

    Python 提供了廣泛的標準函式庫,涵蓋網路、數據處理、圖形界面等多方面。此外,強大的第三方生態系如 NumPy、Pandas、TensorFlow 使 Python 成為多功能的開發工具。

    跨平台的特性

    Python 是跨平台的語言,無論是 Windows、macOS 還是 Linux,都能執行相同的 Python 程式,極大提高了開發的靈活性。

    廣泛應用於多個領域

    Python 在多個領域中發揮重要作用,例如資料科學、人工智慧、網頁開發、自動化腳本和遊戲開發等,讓開發者可以用一種語言處理多種需求。

    活躍的社群支持

    Python 擁有一個龐大的全球社群,無論是初學者還是資深開發者,都能輕易找到教學資源、討論群組和技術支持。

    高效的開發速度

    Python 提供了直觀的語法和強大的工具,讓開發者能更快地實現程式設計,縮短產品的開發週期。



    Python 開發環境

    Anaconda

    什麼是 Anaconda?

    Anaconda 是一個開放源碼的 Python 和 R 編程平台,專為科學計算設計,包括數據科學、機器學習、人工智慧和大數據分析等應用。

    主要功能

    適合對象

    Anaconda 適合以下領域的使用者:

    如何安裝 Anaconda?

    1. 訪問 Anaconda 官方網站
    2. 選擇適合的作業系統版本,下載對應的安裝檔案。
    3. 按照安裝向導完成安裝,並配置環境變數(可選)。

    常見問題

    以下是使用者常遇到的問題:



    Jupyter

    什麼是 Jupyter?

    Jupyter 是一個開放源碼的交互式計算環境,支援多種程式語言,主要用於數據科學、機器學習和學術研究。

  • Jupyter

    核心特點

    主要組件

    應用範圍

    Jupyter 被廣泛應用於以下領域:

    如何使用 Jupyter?

    1. 安裝 Anaconda 或獨立安裝 Jupyter。
    2. 在終端機輸入 jupyter notebook 啟動 Jupyter Notebook。
    3. 透過瀏覽器進入編輯介面,創建和運行 Notebook。

    優勢與挑戰



    Visual Studio Code Python開發環境

    安裝Visual Studio Code

    前往 Visual Studio Code官方網站,下載並安裝適合您作業系統的版本。

    安裝Python擴展

    在Visual Studio Code中,透過以下步驟安裝Python擴展:

    1. 點擊左側的擴展圖示。
    2. 搜尋「Python」。
    3. 選擇由Microsoft提供的Python擴展並點擊「安裝」。

    安裝Python

    確保系統已安裝Python。可以從 Python官方網站 下載並安裝。

    安裝完成後,在命令列輸入以下指令確認安裝成功:

    python --version
    # 或
    python3 --version

    設定Python解譯器

    打開您的Python專案或檔案,點擊Visual Studio Code右下角的「Python」狀態欄,選擇適當的Python解譯器。

    執行Python程式

    在編輯器中開啟Python檔案,使用以下方式執行程式:

    1. 右鍵檔案內容,選擇「Run Python File in Terminal」。
    2. 或使用快捷鍵 Ctrl + Shift + P,搜尋「Run Python File」並執行。

    安裝必要套件

    如果需要安裝第三方套件,可以使用內建終端機輸入:

    pip install 套件名稱

    啟用自動完成與除錯

    透過Python擴展提供的功能,可享受自動完成與強大的除錯工具:

    1. 點擊左側的除錯圖示。
    2. 選擇「Create a launch.json file」,選擇Python。
    3. 設置完成後即可按F5啟用除錯模式。

    常用快捷鍵

    以下是幾個常用快捷鍵:



    VS Code

  • vscode/Vidual Studio Code

    VS Code設定Python執行參數

    修改launch.json

    若需要在執行Python程式時傳遞參數,可以透過設定 launch.json 完成:

    1. 點擊左側的「Run and Debug」圖示。
    2. 點擊「create a launch.json file」或「Add Configuration」。
    3. 選擇「Python」作為環境。
    4. 在生成的 launch.json 文件中修改相關設定。

    設定program與args參數

    以下是一個範例配置,包含程式路徑和執行時的參數:

    {
        "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的用途

    args 中可以傳遞命令列參數,例如:

    在程式中讀取參數

    使用 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


    VS Code Python Debug 模式

    啟用 Debug 模式

    1. 安裝 Python Extension 擴展。

    2. 在 VS Code 中開啟您的 Python 專案。

    3. 按下 F5 或點擊左側活動欄的 Debug 圖示。

    設定 launch.json

    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. 可使用條件中斷點:右鍵點擊中斷點並選擇「編輯條件」。

    調試功能

    檢查變數

    1. 在 Debug 面板的「變數」區域檢視目前變數狀態。

    2. 可在「監視」區域手動加入特定表達式。

    使用 Debug Console

    1. 在 Debug Console 中輸入 Python 指令以即時檢查程式狀態。

    2. 可執行變數查詢、呼叫函式等操作。



    pip 使用指南

    1. 什麼是 pip?

    2. pip 的基本操作

    3. 進階功能

    4. 常見問題與解決方案

    5. pip 的最佳實踐



    pip/cache/http-v2 資料夾

    1. 什麼是 pip/cache/http-v2 資料夾?

    2. http-v2 資料夾的用途

    3. http-v2 資料夾的管理

    4. 注意事項



    在 Visual Studio Code 中設定 Python 路徑

    步驟 1:安裝 Python 與 VS Code

    確保已安裝 Python 並將其加入系統環境變數,然後下載並安裝 Visual Studio Code。

    步驟 2:安裝 Python 擴充套件

    開啟 Visual Studio Code,點擊左側的 Extensions 圖示,搜尋 Python,然後安裝 Microsoft 提供的 Python 擴充套件。

    步驟 3:檢查 Python 安裝路徑

    在終端機輸入以下指令來確認 Python 的安裝路徑:

    which python

    或(Windows 系統):

    where python

    步驟 4:設定 Python 路徑

    在 Visual Studio Code 中,按 Ctrl + Shift + P,輸入並選擇 Python: Select Interpreter

    在清單中選擇正確的 Python 路徑。如果未顯示,請手動輸入完整路徑。

    步驟 5:確認設定

    開啟終端機並執行 python --version 來確認選定的 Python 解釋器版本正確。

    附加資訊

    如果需要特定專案的 Python 路徑,可以在專案根目錄新增 .vscode/settings.json 檔案,並加入以下內容:

    {
      "python.pythonPath": "你的 Python 完整路徑"
    }

    替換 你的 Python 完整路徑 為實際路徑。



    Python 基本資料結構

    陣列

    什麼是陣列?

    在 Python 中,陣列是一種用於存儲多個相同類型元素的資料結構。雖然 Python 本身並沒有內建的陣列型別,但可以使用 listarray 模組來實現類似的功能。

    使用 List 作為陣列

    list 是 Python 的內建資料結構,可以儲存多種類型的資料,但也可以用來模擬陣列。

    my_list = [1, 2, 3, 4, 5]
    print(my_list[0])  # 輸出: 1

    使用 array 模組

    如果需要真正的陣列(所有元素必須是相同類型),可以使用 array 模組。

    import array
    
    my_array = array.array('i', [1, 2, 3, 4, 5])
    print(my_array[0])  # 輸出: 1

    在這裡,'i' 表示陣列中的元素是整數。

    array 模組的基本操作

    以下是一些基本操作:

    陣列與 NumPy

    對於需要進行數值運算的情況,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 是科學計算的首選工具。



    陣列的動態增減

    使用 List 進行動態操作

    在 Python 中,list 是動態資料結構,可以輕鬆進行元素的新增與移除。

    新增元素

    可以使用以下方法新增元素:

    # 新增元素示例
    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]
    

    移除元素

    可以使用以下方法移除元素:

    # 移除元素示例
    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 模組的動態操作

    對於需要相同類型元素的情況,可以使用 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 提供了多種方法來實現陣列的動態增減,listarray 模組分別適合不同需求。對於更多功能需求,也可以考慮使用 numpy



    判斷字串是否為數字

    使用 str.isdigit()

    isdigit() 方法可以用於檢查字串是否只包含數字字符。

    # 示例
    string = "12345"
    if string.isdigit():
        print("是數字")
    else:
        print("不是數字")
    

    注意:isdigit() 無法處理小數點或負號。

    使用 str.replace() 處理小數

    如果需要檢查帶有小數點的字串,可以先移除小數點再使用 isdigit()

    # 示例
    string = "123.45"
    if string.replace(".", "").isdigit():
        print("是數字")
    else:
        print("不是數字")
    

    此方法不適用於負數。

    使用 try-except 轉換為數字

    最通用的方法是嘗試將字串轉換為浮點數或整數,並捕捉轉換失敗的異常。

    # 示例
    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,我們希望找到在 strAstrB 出現之前的部分。例如:

    str1 = "Hello World, this is a test. Stop here or continue."
    strA = "Stop"
    strB = "continue"
    

    目標是獲取 "Hello World, this is a test. "

    使用 re.split()

    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()

    re.search() 可以用來匹配 strAstrB,並取得匹配前的內容:

    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() 方法

    find() 方法可以手動搜尋最早出現的 strAstrB,然後擷取對應部分:

    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.match()

    re.match()

    Python 的 re.match 是正則表達式模組中的一個函式,用於從字串的開頭進行匹配。 如果匹配成功,則返回一個 Match 物件;否則返回 None

    語法

    re.match(pattern, string, flags=0)

    參數說明:

    常用屬性和方法

    使用範例

    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!
        

    注意事項

    正則表達式

    正則表達式(Regular Expression,簡稱 Regex)是一種用於描述字串匹配規則的語法,常用於搜尋、替換或驗證字串。 在 Python 的 re 模組中,pattern 就是定義這些規則的核心部分。

    基本語法元素

    進階用法

    範例

    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() 的應用

    基本用法

    re.search() 用於在字串中搜尋符合正則表達式的第一個匹配項,並回傳 Match 物件,如果沒有匹配則回傳 None

    import re
    
    text = "Hello 2024!"
    match = re.search(r"\d+", text)
    
    if match:
        print("找到數字:", match.group())  # 2024
    

    返回 Match 物件

    re.search() 找到匹配時,會返回 Match 物件,可透過以下方法存取資訊:

    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.findall() 的比較

    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
    

    搭配 OR 運算符

    使用 (?:...|...) 可以讓 | 運算符影響匹配內容,但不影響群組存取。

    import re
    
    text = "bar123"
    pattern = r"(?:foo|bar|baz)\d+"
    
    match = re.search(pattern, text)
    print(match.group())  # bar123
    

    應用於 --user-data-dir 解析

    在解析 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
    

    結論

    (?:...) 在正則表達式中能提高效能,避免影響群組索引,並適用於 | 運算及特定條件匹配,使程式碼更高效且清晰。



    Python 流程

    Python 中的類別(Class)介紹

    1. 基本類別概念

    Python 的類別(Class)是用於封裝數據和行為的結構。類別用於創建物件,物件是類別的實例。例如:
    class MyClass:
        def __init__(self, value):
            self.value = value
    
        def display(self):
            print(f"Value: {self.value}")
    
    obj = MyClass(10)
    obj.display()  # 輸出: Value: 10
    

    2. 靜態方法(Static Method)

    靜態方法使用 `@staticmethod` 裝飾器定義,與類別和物件無關,不能訪問類別屬性或物件屬性。適用於一些工具性功能:

    class MyClass:
        @staticmethod
        def add(a, b):
            return a + b
    
    result = MyClass.add(5, 3)
    print(result)  # 輸出: 8
    

    3. 類別方法(Class Method)

    類別方法使用 `@classmethod` 裝飾器定義,第一個參數是類別本身(通常命名為 `cls`),可以訪問類別屬性:

    class MyClass:
        count = 0
    
        @classmethod
        def increment_count(cls):
            cls.count += 1
    
    MyClass.increment_count()
    print(MyClass.count)  # 輸出: 1
    

    4. 繼承與多型

    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!
    

    5. 類別屬性與物件屬性

    類別屬性是屬於整個類別的,所有物件共享;物件屬性則屬於每個物件:

    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
    

    6. 使用 object 作為基類

    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
    

    7. 總結

    - **靜態方法(Static Method)**:與類別無關,主要用於工具性功能。 - **類別方法(Class Method)**:操作類別層級的數據。 - **物件方法(Instance Method)**:操作物件層級的數據。 - **繼承與多型**:支援代碼重用與靈活設計。 - **object 基類**:提供基本方法,讓所有類別具備一致的行為。

    Python 的類別繼承

    1. 基本繼承概念

    在 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!
    

    2. 子類覆寫父類方法

    子類可以覆寫(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!
    

    3. 使用 super() 呼叫父類方法

    在子類中可以透過 `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!
    

    4. 多重繼承

    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! (依據繼承順序)
    

    5. 方法解析順序(MRO)

    多重繼承使用 MRO(Method Resolution Order)確定方法的解析順序。可以使用 `__mro__` 屬性檢查:

    print(Child.__mro__)
    # 輸出: (, , , )
    

    6. 抽象基類

    使用 `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!
    

    7. 總結

    - 繼承讓類別代碼更具重用性和擴展性。 - 子類可以覆寫父類方法,並用 `super()` 呼叫父類方法。 - 支援多重繼承,但需注意方法解析順序(MRO)。 - 抽象基類可用於強制子類實現特定方法,適合介面設計。

    建立繼承 ClassB 的臨時類別

    範例程式碼

    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()
    

    解釋

    1. type() 函數:
      type('TempClass', (ClassB,), {...})
      - 'TempClass':新類別名稱。
      - (ClassB,):基礎類別的元組,這裡只有 ClassB。
      - {...}:新增的屬性或方法。
    2. Lambda 函數用於覆蓋方法:
      - 自訂 greet 方法先印出新訊息,再透過 super() 呼叫父類別的 greet

    輸出結果

    Hello from TempClass!
    Hello from ClassB!


    inspect - 拿到目前function的parameters和當前值

    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__}")
        

    程式說明

    執行結果

    對於範例中的類別,執行結果如下:

    
    屬性 '__module__' 屬於類別: SubClass
    屬性 'sub_attr' 屬於類別: SubClass
    屬性 '__doc__' 屬於類別: SubClass
    屬性 'base_attr' 屬於類別: BaseClass
        


    @staticmethod 與 @classmethod 的差異

    在 Python 中,@staticmethod@classmethod 這兩個裝飾器都可以定義不需要實例化類別就能調用的方法,但它們的用途和行為有所不同。

    @staticmethod

    @staticmethod 範例:

    class MyClass:
        @staticmethod
        def static_method(x, y):
            return x + y
    
    # 無需建立實例即可調用靜態方法
    result = MyClass.static_method(5, 10)  # 結果:15
        

    重點@staticmethod 無法訪問類別(cls)或實例(self)。

    @classmethod

    @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()  # 輸出: 調用靜態方法
        

    工作原理:

    總結

    雖然 Python 沒有內建「默認靜態方法」或「默認類別方法」,但通過使用靜態變數與懶加載技巧,你可以在第一次調用靜態或類別方法時自動執行初始化邏輯,並確保該邏輯只會被執行一次。



    Pandas 資料分析工具

    什麼是 Pandas?

    Pandas 是一個基於 Python 的資料分析與操作工具,專門用於處理結構化數據,例如表格數據或時間序列數據。

    Pandas 的核心數據結構

    Pandas 的主要功能

    使用範例

    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 提供高效、靈活且直觀的操作方式,特別適合進行數據分析與處理,是數據科學和機器學習中不可或缺的工具之一。

    結論

    Pandas 是一個功能強大的資料分析工具,無論是入門還是高階使用者,都能受益於其簡單易用的設計和廣泛的功能。



    Python Googletrans

    安裝 Googletrans

    首先,您需要安裝 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)
        

    支援的語言代碼

    您可以翻譯多種語言,以下是常見的語言代碼:

    注意事項

    Googletrans 是非官方的 Google 翻譯 API,因此有可能因為 Google 端的更改而停止運作。如果發現翻譯功能失效,請考慮使用其他翻譯 API,例如 Google 官方的 Cloud Translation API。



    Python 其他翻譯kit

    DeepL Translator

    DeepL 提供準確性較高的翻譯服務,但需要 API key 才能使用其開發者 API。

    Microsoft Translator

    由 Microsoft 提供的翻譯工具,支援多語言翻譯,但需使用 Azure 的 API key 設定。

    Amazon Translate

    Amazon Web Services (AWS) 提供的翻譯服務,針對多語言文本進行高效翻譯,需透過 AWS 提供的 API key 訪問。

    LibreTranslate

    LibreTranslate 是開源的翻譯工具,可自行架設服務器,不需要 API key。部分第三方公共伺服器也提供無需 API key 的使用選項。

    TextBlob

    TextBlob 是一個基於自然語言處理的工具,內建 Google Translate 的功能,但較舊版本的實現可無需 API key,可能需要注意版本支持。

    MyMemory

    MyMemory 提供基於記憶的翻譯,部分功能不需要 API key,但高級使用可能需申請。

    結論

    在 Googletrans 的競爭對手中,像 LibreTranslate 和部分版本的 TextBlob 提供了無需 API key 的選擇。如果需要完全免費且無需額外設定的工具,可考慮這些選項。



    Python 查詢中文的注音

    以下範例將展示如何使用 Python 來查詢中文字符的所有注音。我們使用 pypinyin 套件來取得中文字的拼音,並自訂拼音轉注音符號的對應表。

    步驟 1:安裝 pypinyin 套件

    pip install pypinyin

    步驟 2:Python 程式碼範例

    以下是 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)
    
    

    說明



    logging 套件

    Python 的 logging 套件是一個強大的內建模組,用於應用程式中進行有效的日誌管理。無論是記錄調試信息、錯誤追蹤,還是性能監控,logging 套件都能提供多層級、多格式的日誌記錄方式。

    基本概念

    範例代碼

    以下是一個基本的 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 支援以下日誌級別:

    自訂輸出格式

    可以使用 Formatter 類來定義日誌的輸出格式。例如:

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    這個格式會輸出類似於以下內容:

    2024-10-25 10:00:00 - my_logger - INFO - 這是一條信息訊息

    小結

    logging 套件提供了多樣化的日誌管理選項,讓開發者可以根據需求自訂日誌級別、輸出格式及目的地,提升應用程式的可維護性及除錯效率。



    Logging Handler

    在 Python 的 logging 套件中,Handler 是一個關鍵的組件,負責定義日誌的輸出位置。不同的處理器可以將日誌輸出到不同的目標位置,包括控制台、文件、網絡、甚至是郵件。StreamHandler 是最常用的處理器之一,它負責將日誌輸出到控制台。

    主要處理器(Handler)

    logging 中,一些常見的 Handler 包括:

    StreamHandler 與 Console Output 的關係

    StreamHandler 是控制台輸出最常用的處理器,它通常會將日誌消息發送到標準錯誤(stderr)。透過設定 StreamHandler,可以讓日誌直接在控制台顯示,適合即時監控系統的狀態。

    如果不希望日誌顯示在控制台上,可以從 Logger 中移除 StreamHandler,或者改用 NullHandler 來避免輸出。

    範例代碼:移除 Console Output

    以下範例展示了如何配置 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 避免 Console Output

    可以使用 NullHandler 來禁用日誌的所有輸出:

    import logging
    
    # 設定 Logger 並添加 NullHandler
    logger = logging.getLogger('my_logger')
    logger.addHandler(logging.NullHandler())
    
    # 這條訊息不會顯示在控制台
    logger.info("這條消息將不會顯示")

    小結

    Handlerlogging 套件中定義輸出位置的組件。透過 StreamHandler,日誌消息可以顯示在控制台,便於即時監控。若不需要控制台輸出,可以移除 StreamHandler 或使用 NullHandler 來禁用日誌輸出。



    呼叫 Web API 並解析 JSON 回應

    使用 requests 模組呼叫 API

    Python 的 `requests` 模組是呼叫 Web API 的常用工具,簡單易用。以下是基本範例:
    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 回應

    `requests` 模組自帶的 `.json()` 方法可以輕鬆將 JSON 格式的回應轉換為 Python 資料結構(字典或清單):
    # 解析 JSON 回應
    data = response.json()
    
    # 存取 JSON 資料
    print(data["key1"])
    print(data["key2"]["subkey"])
    

    範例:呼叫和解析

    以下是一個完整範例,演示如何呼叫 API 並解析 JSON 回應:
    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}")
    

    處理 JSON 例外

    在解析 JSON 回應時,可能會遇到例外狀況,可以使用 `try-except` 處理:
    try:
        data = response.json()
        print(data)
    except ValueError:
        print("回應不是有效的 JSON 格式")
    

    注意事項

    1. **檢查 API 文件**:不同 API 的請求參數和回應格式可能不同,請詳閱 API 文件。 2. **處理錯誤回應**:確保檢查 HTTP 狀態碼並處理非 200 的回應。 3. **安全性**:若需提供 API 金鑰或敏感資料,請勿直接硬編碼在程式中,應使用環境變數或安全的配置文件。

    總結

    透過 Python 的 `requests` 模組,可以輕鬆呼叫 Web API 並解析 JSON 回應。正確處理回應和錯誤能提升程式的穩定性和可靠性。

    Python資料庫

    Python常用資料庫套件

    關聯式資料庫(SQL)

    SQLite(內建)

    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(PyMySQL)

    用於連接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(psycopg2)

    用於連接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()

    SQL Server(pyodbc)

    用於連接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()

    非關聯式資料庫(NoSQL)

    MongoDB(pymongo)

    適用於文件型資料庫。

    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()))

    Redis(redis-py)

    適用於快取與高效能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"))

    Elasticsearch(elasticsearch-py)

    適用於全文搜尋與分析。

    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": {}}))

    ORM框架

    SQLAlchemy

    支援多種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())

    結論



    PyMySQL

    安裝PyMySQL

    使用以下指令安裝PyMySQL:

    pip install pymysql

    連接MySQL資料庫

    使用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()

    執行SQL語句

    執行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注入

    使用參數化查詢來防止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

    若要在Python中執行MySQL的儲存程序,可以使用 mysql-connector-pythonPyMySQL

    安裝套件

    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()

    使用SQL Server

    若要在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()

    使用PostgreSQL

    若要在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()

    注意事項



    Python爬蟲

    Requests + BeautifulSoup

    這是最常見的爬蟲組合,適合初學者,用於解析靜態網頁。

    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)

    Scrapy

    一個強大的爬蟲框架,適合大型爬蟲專案,支持多線程和分佈式爬蟲。

    pip install scrapy

    使用範例:

    scrapy startproject myproject

    在專案內建立爬蟲模組,運行爬取命令。

    Selenium

    適合需要模擬使用者操作的動態網頁爬取,例如處理JavaScript渲染的內容。

    pip install selenium

    使用範例:

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    driver.get("https://example.com")
    print(driver.title)
    driver.quit()

    Playwright

    另一個處理動態網頁的工具,相比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()

    Pyppeteer

    基於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())

    HTTPX

    用於發送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())


    Python BeautifulSoup 爬蟲程式

    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


    使用 BeautifulSoup 查找特定標籤和類別中的文字值

    範例場景

    假設我們有以下的 HTML 結構,想要提取 `` 標籤中類別為 `xxxclass` 的文字值:
    
    
        需要提取的文字
        其他文字
    
    
    

    使用 BeautifulSoup 查找並提取文字

    以下是使用 `BeautifulSoup` 的 Python 程式碼:
    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("未找到匹配的標籤")
    

    方法說明

    1. **`find(tag, class_=...)`**: - `tag`:指定要查找的 HTML 標籤,例如 `span`。 - `class_`:指定類別名,例如 `xxxclass`。需要注意 `class_` 是用底線避免與 Python 的保留字 `class` 衝突。 2. **`.text`**:提取標籤內的文字內容。

    查找多個匹配項

    若需要提取多個標籤,可以使用 `find_all`:
    # 查找所有匹配的  標籤
    span_tags = soup.find_all('span', class_='xxxclass')
    
    # 提取每個標籤的文字
    for tag in span_tags:
        print(tag.text)
    

    其他篩選條件

    1. **按多個屬性篩選**:
       span_tag = soup.find('span', {'class': 'xxxclass', 'id': 'specific-id'})
       
    2. **使用正則表達式匹配類別**:
       import re
       span_tag = soup.find('span', class_=re.compile(r'^xxx'))
       

    注意事項

    1. **HTML 格式**:確保 HTML 是有效的,否則解析可能出現問題。 2. **空結果處理**:查找不到時返回 `None`,應檢查結果是否為空以避免錯誤。

    總結

    透過 `BeautifulSoup` 的 `find` 或 `find_all` 方法,可以輕鬆提取特定標籤和類別中的文字內容。靈活使用篩選條件和屬性匹配可以處理更複雜的場景。

    by 卡打 - 2024/12/22



    Selenium

    什麼是 Selenium?

    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()
    
    

    優點與挑戰

    by 卡打 - 2024/12/27



    Selenium Chrome 使用特定使用者

    安裝必要套件

    確保已安裝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()

    注意事項

    應用場景

    by 卡打 - 2025/01/18



    獲取所有 user_data_dir

    1. 安裝必要的庫

    確保已安裝 seleniumpsutil

    pip install selenium psutil

    2. 取得所有使用中的 Chrome user_data_dir

    以下程式碼會掃描所有運行中的 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())

    3. 在 Selenium 中使用特定 user_data_dir

    找到目標 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")

    4. 結論

    透過 psutil 解析運行中的 Chrome 進程,即可獲取所有 user-data-dir,並在 Selenium 中使用特定的 user_data_dir 啟動瀏覽器。

    by 卡打 - 2025/03/12



    如何從 Chrome 使用者資料目錄取得使用者名稱

    問題說明

    若要從 Chrome 使用者資料目錄中獲取使用者名稱,您需要訪問該目錄中的檔案,通常是位於以下路徑:

    這些資料夾包含許多檔案,您可以讀取 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

    當您讀取 Local State 檔案並將其解析為 JSON 時,可以從中取得許多資料,例如:

    在大多數情況下,使用者名稱將位於 profile 下,並可通過上述方法提取。

    注意事項

    結論

    通過解析 Local State 檔案中的 JSON 資料,您可以輕鬆地獲取 Chrome 使用者的名稱。

    by 卡打 - 2025/03/12



    如何從 Local State 檔案中獲取所有使用者

    問題說明

    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))
    

    解析 Local State 中的使用者資料

    在 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 中所有使用者的名稱。這使得可以輕鬆地列出所有帳戶。

    by 卡打 - 2025/03/12



    如何從 Local State 檔案中獲取使用者名稱及其對應的子目錄

    問題說明

    在 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 中的資料結構

    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"
                }
            }
        }
    }
    

    注意事項

    結論

    通過解析 Local State 檔案,您可以獲取所有使用者的名稱及其對應的配置子目錄。這使得您可以輕鬆地找到每個使用者的配置資料位置。

    by 卡打 - 2025/03/12



    如何從 Chrome 使用者資料中獲取 Gmail 帳號

    問題說明

    若要從 Chrome 使用者資料目錄中獲取 Gmail 帳號,您需要從 Chrome 配置資料中提取相關資訊。這通常可以通過解析 Chrome 的使用者資料檔案來實現,特別是 Google 相關的帳戶資料。

    步驟:讀取 Profile 檔案並解析

    每個 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 檔案

    Web Data 檔案包含了 Chrome 中的多種登入資料,包括帳號的名稱、密碼和其他相關資訊。在此例中,我們尋找其中的 email 欄位,並檢查是否包含 Gmail 的郵箱。

    示範:Web Data 檔案結構

    以下是 Web Data 檔案的一部分結構範例:

    
    {
        "accounts": [
            {
                "email": "[email protected]",
                "password": "encrypted_password_1"
            },
            {
                "email": "[email protected]",
                "password": "encrypted_password_2"
            }
        ]
    }
    

    注意事項

    結論

    通過解析 Chrome 使用者資料中的 Web Data 檔案,您可以輕鬆地獲取使用者的 Gmail 帳號。如果該使用者已經登入 Gmail 帳號,則相應的電子郵件會顯示在資料中。

    by 卡打 - 2025/03/12



    模擬使用者操作瀏覽網站內頁面

    步驟一:使用網頁自動化工具

    常見的網頁自動化工具包括 Selenium 和 Playwright。這些工具可以模擬點擊、輸入文字以及其他使用者操作。

    步驟二:抓取所有連結

    使用工具如 BeautifulSoup 或 Playwright,獲取網站上的所有超連結 (<a href>),以此來建立需要瀏覽的頁面列表。

    步驟三:設定瀏覽器模擬

    透過 Selenium 或 Playwright 開啟瀏覽器並模擬使用者的行為,例如點擊按鈕、滾動頁面,甚至觸發動態內容。

    步驟四:處理 JavaScript 動態內容

    現代網站通常包含大量動態生成的內容,可以使用 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()
        

    注意事項

    在進行網站瀏覽和模擬操作時,請遵守相關網站的使用條款,避免造成過多的伺服器負擔或違反法律。

    by 卡打 - 2024/11/25



    使用 WebDriver 執行測試並設計逐步執行的方式

    概述

    在使用 WebDriver(例如 Selenium WebDriver)進行測試時,可以設計逐步執行的方式來排查問題或模擬用戶操作。以下是一些常見的設計方式。

    方法 1:使用顯式等待

    透過顯式等待,可以確保每一步執行完成後再進行下一步:
    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()
    

    方法 2:手動插入暫停

    透過 `time.sleep()` 暫停測試進程,以便觀察每一步的執行效果:
    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` 不建議用於正式測試,僅適用於調試過程。

    方法 3:逐步執行與斷點設計

    透過在代碼中加入條件斷點或輸入提示,可以進行逐步調試:
    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()
    

    方法 4:使用測試框架設計可控制執行

    借助測試框架(如 pytest 或 unittest),可以更靈活地控制測試執行:
    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()
    

    注意事項

    1. **等待時間設置**:使用顯式等待代替固定暫停以提高效率和穩定性。 2. **逐步測試用於調試**:逐步執行設計適用於調試過程,不適合長時間執行的自動化測試。 3. **測試框架的靈活性**:使用框架可以更好地組織測試用例和測試步驟。

    總結

    透過顯式等待、手動斷點、暫停時間或結合測試框架,可以有效設計逐步執行的測試流程,方便調試與優化操作。

    by 卡打 - 2024/12/25



    使用 Selenium 搜尋特定行開頭文字並提取資料

    程式碼範例

    
    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

    注意事項

    by 卡打 - 2024/12/27



    使用 Python 從 Thunderbird 提取重要電子郵件

    步驟 1:準備環境

    要從 Thunderbird 提取電子郵件,可以使用 Python 的 IMAP 協議庫,例如 imaplib 或第三方庫 imapclient。首先,請確保 Thunderbird 已啟用 IMAP 協議並允許外部應用程式連接。

    步驟 2:安裝所需的 Python 庫

    使用 pip 安裝相關庫:

    pip install imapclient pyzmail36
        

    步驟 3:連接到郵件伺服器

    使用以下代碼連接到電子郵件伺服器並提取重要電子郵件:

    
    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')}")
        

    步驟 4:注意事項

    步驟 5:測試和調試

    執行上述代碼,查看是否能成功提取標示為重要的電子郵件。如果有任何連接問題,可以檢查伺服器設置,或者在 IMAP 協議層進行更詳細的調試。

    這樣,您可以成功使用 Python 從 Thunderbird 提取重要電子郵件。

    by 卡打 - 2024/11/17



    PyAutoGUI

    安裝PyAutoGUI

    使用以下指令安裝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) 可立即停止程式

    常見應用

    by 卡打 - 2025/01/18



    控制 Surfshark VPN

    前置準備

    如果 Surfshark VPN 沒有提供命令列工具(如 surfshark-cli),則需要透過 GUI 自動化工具(如 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()
    
        

    實際操作中的注意事項

    替代方法

    如果座標方式不穩定,可以使用影像識別(如 pyautogui.locateOnScreen())來找到按鈕位置,增加靈活性。

    by 卡打 - 2024/11/26



    Kivy - Python GUI

    Kivy 是一個開源的 Python 框架,用來快速開發多點觸控應用程序。它的設計初衷是跨平台支持,允許開發者在 Windows、macOS、Linux、iOS 和 Android 等多個平台上運行同一份代碼。Kivy 特別適合構建用於手機、平板電腦和桌面設備的 GUI 應用程序,並且它有良好的多點觸控支持。

    Kivy 的主要功能

    如何使用 Kivy

    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()
        

    安裝 Kivy

    可以通過 pip 安裝 Kivy:

    pip install kivy

    Kivy 的應用場景

    Kivy 適用於多種應用場景,包括但不限於:

    by 卡打 - 2024/10/17



    Python Kivy 如何遠端顯示

    Kivy 是一個用於建立跨平台應用的 Python 框架,但它通常運行在本地裝置上。要將 Kivy 應用程式顯示在遠端,您可以考慮以下幾種方式:

    1. 使用 VNC 或遠端桌面工具

    您可以使用 VNC(Virtual Network Computing)或其他遠端桌面工具(如 RDP、TeamViewer 等)來遠端控制並顯示 Kivy 應用程式。

    2. 使用 X11 Forwarding(適用於 Linux)

    對於使用 Linux 的用戶,您可以使用 X11 forwarding 在遠端顯示圖形界面:

    3. 使用 Kivy + Flask 做為 Web 應用顯示

    您可以使用 Flask 或其他 Web 框架將 Kivy 應用程式部分功能暴露給遠端用戶,並使用 Web 瀏覽器顯示:

    4. Docker + Kivy + VNC

    如果您希望在容器化環境中運行 Kivy 應用,您可以使用 Docker 和 VNC 進行設置:

    by 卡打 - 2024/10/23



    ModuleNotFoundError: No module named 'kivy.garden.tickmarker'

    This error indicates that the tickmarker module from Kivy's Garden is not installed. To fix this issue, follow the steps below:

    Steps to Resolve the Issue

    1. Install Kivy Garden
      If you don’t already have Garden installed, open your terminal or command prompt and run the following command:
      pip install kivy-garden
    2. Install the Tickmarker Widget
      After installing Kivy Garden, install the tickmarker widget by running:
      garden install tickmarker

    Once you've done these steps, try running your Kivy application again.

    by 卡打 - 2024/10/23



    Gradio

    Gradio 是一個開源的 Python 庫,旨在讓機器學習模型變得更加可訪問和易於互動。通過簡單的代碼,您可以快速為您的機器學習模型建立一個網頁界面,供他人測試和使用。

    Gradio 的主要特點

    如何使用 Gradio

    Gradio 的用法非常簡單,以下是一個基本的範例,顯示如何創建一個簡單的文字輸入和輸出的介面:

    import gradio as gr
    
    # 定義處理輸入數據的函數
    def greet(name):
        return "你好," + name + "!"
    
    # 創建 Gradio 介面
    iface = gr.Interface(fn=greet, inputs="text", outputs="text")
    
    # 啟動介面
    iface.launch()

    上面的程式碼將創建一個簡單的網頁介面,讓使用者可以輸入名字,然後顯示個人化的問候語。

    Gradio 的應用場景

    結論

    Gradio 為開發者提供了一個簡單且強大的工具,能夠快速將機器學習模型轉化為網頁應用,讓更廣泛的使用者能夠輕鬆地測試和體驗 AI 的成果。無論是用於個人項目還是團隊合作,Gradio 都是推廣和展示模型的理想選擇。

    by 卡打 - 2024/10/24



    Gradio 輸出重定向到 HTTP 伺服器頁面

    如果想將 Gradio 介面的輸出重定向到 Apache HTTP 伺服器的頁面(如 `/results`),您可以使用 Python 的 requests 模組來將 Gradio 的結果傳送到伺服器。以下是如何將 Gradio 和 Apache 整合的基本步驟:

    步驟 1: 設定 HTTP 伺服器

    首先,確保您的 Apache HTTP 伺服器正在運行,並且已經配置好一個能夠處理數據的端點(例如 /results)。這個端點可以是 PHP、Python 或其他後端語言來處理傳入的數據。

    步驟 2: 創建 Gradio 應用程式

    以下是如何編寫 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()

    步驟 3: 伺服器端處理

    您的 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 環境中。

    by 卡打 - 2024/10/24



    在 Web伺服器顯示 Gradio 內容

    方法一:使用 iframe 嵌入 Gradio 頁面

    在 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>
            

    方法二:使用反向代理 (Reverse Proxy) 將 Gradio 介面整合至 Apache URL

    如果希望透過 Apache 的 URL 直接訪問 Gradio 介面,可以配置反向代理。這樣無需顯示原始的 Gradio URL。

    步驟

    1. 啟用 Apache 的 mod_proxymod_proxy_http 模組。執行以下指令:
    2. 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
    3. 在 Apache 的配置文件中,新增以下反向代理設置,將 Gradio 介面反向代理至 Apache 的特定路徑 (例如:/gradio)。
    4. <Location "/gradio">
          ProxyPass "http://localhost:7860/"
          ProxyPassReverse "http://localhost:7860/"
      </Location>
                  
    5. 儲存配置並重新啟動 Apache 服務:
    6. sudo systemctl restart apache2

    完成後,您可以透過 http://your-apache-server-address/gradio 在 Apache 頁面中顯示來自 Gradio 的介面內容。

    by 卡打 - 2024/10/26



    解決 Gradio Static Assets 不透過 Apache Proxy 的問題

    步驟 1:啟用 Proxy 和 Proxy HTTP 模組

    在 Apache 中,確保已啟用 proxyproxy_http 模組。若尚未啟用,可以執行以下指令:

    sudo a2enmod proxy
    sudo a2enmod proxy_http
        

    步驟 2:更新 Apache Virtual Host 配置

    在 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>
    
        

    步驟 3:重啟 Apache

    完成設定後,請重啟 Apache 以套用更改:

    sudo systemctl restart apache2

    這樣的配置可以明確處理對 Gradio 靜態資源 (如 theme.css) 的請求,應能解決缺少樣式的問題。如果 Gradio 的靜態檔案路徑非 /static/,請根據實際情況調整路徑。

    by 卡打 - 2024/11/06



    Gradio 中的 DataFrame 元件

    在 Gradio 中可以使用 gr.DataFrame 元件來顯示或編輯表格數據,例如顯示 Pandas DataFrame 或其他表格格式的數據。在這裡,我們將介紹如何在 Gradio 應用中使用 DataFrame 元件來創建交互式的數據表格。

    1. 安裝 Gradio

    如果尚未安裝 Gradio,可以使用以下命令安裝:

    pip install gradio

    2. 使用 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()

    說明

    3. 使用 gr.DataFrame 進行互動編輯

    如果希望讓使用者能夠編輯表格,可以在 gr.DataFrame 中設置 editable=True,允許使用者修改表格數據:

    interface = gr.Interface(fn=show_dataframe, outputs=gr.DataFrame(editable=True), title="可編輯的人員數據表")

    結果

    啟動後的應用會顯示可編輯的表格,使用者可以直接在網頁上對數據進行修改。

    by 卡打 - 2024/10/31



    在 Python 中強制終止 Gradio 伺服器程序

    步驟 1:查找 Gradio 程序的 PID

    可以使用 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'])
    

    步驟 2:強制終止 Gradio 程序

    找到 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 程序。

    by 卡打 - 2024/11/07



    在 Python 中通過監聽埠強制終止 Gradio 伺服器程序

    步驟 1:查找監聽特定埠的程序

    可以使用 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 的程序")
    

    步驟 2:強制終止找到的程序

    找到 PID 後,可以使用 psutil.Processkill() 方法來強制終止程序:

    if pid_to_kill:
        process = psutil.Process(pid_to_kill)
        process.kill()  # 強制終止程序
        print(f"已終止監聽埠 7860 的程序 PID: {pid_to_kill}")
    else:
        print("無法終止程序,因為未找到該 PID")
    

    注意事項

    此程式碼將強制終止任何監聽指定埠的程序。請確認該埠確實為 Gradio 使用,以免誤終止其他服務。

    by 卡打 - 2024/11/07



    Manim - Python Animation

    Manim(Mathematical Animation Engine)是一個用 Python 編寫的動畫庫,特別用來創建數學圖像和動畫。Manim 可以用於生成高品質的動畫,展示數學概念、代碼運行過程,或者任何以圖像和動畫表現的東西。

    Manim 的主要功能

    如何使用 Manim

    Manim 的動畫一般是通過編寫 Python 腳本來完成的,然後生成視頻文件。每個動畫通常包含一個或多個場景 (Scene),而每個場景則由不同的對象 (Mobject) 組成。

    基本範例

    
    from manim import *
    
    class MyFirstScene(Scene):
        def construct(self):
            text = Text("Hello, Manim!")  # 創建一個文字對象
            self.play(Write(text))  # 生成動畫
        

    安裝 Manim

    可以通過 pip 安裝 Manim:

    pip install manim

    by 卡打 - 2024/10/17



    ManimGL

    簡介

    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

    主要特性

    常見問題

    如果遇到安裝或運行問題,可嘗試:

    相關資源

    by 卡打 - 2025/02/15



    Blender 模組介紹

    bpy 模組是一個專門為 Blender 設計的 Python API,允許使用者在 Blender 內透過程式碼來創建、修改以及管理 3D 圖像和動畫。

    什麼是 bpy

    bpy 是 Blender Python 的縮寫,它是一組函數庫,允許使用 Python 腳本來操作 Blender 的核心功能。透過 bpy,使用者可以:

    bpy 的主要模組和功能

    bpy 包含了多個子模組,每個模組都有特定的用途:

    簡單範例:創建一個立方體

    以下是使用 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

    by 卡打 - 2024/10/26




    email: [email protected]
    
    T:0000
    資訊與搜尋 | 回dev首頁 電話: 02-27566655 ,03-5924828 email: [email protected]