跳至頁尾內容
PYTHON 幫助

PyYAML(開發人員工作原理)

PyYAML 是一個 Python 程式庫,作為 YAML 解析器和發送器。 YAML(YAML Ain't Markup Language)是一種人類可讀的資料序列化格式,與 Python 應用程式完美整合,具有良好的錯誤支援、強大的擴展 API 等。 YAML 通常用於配置檔案和不同資料結構語言之間的資料交換,考量人類可讀性。 在本文稍後,我們將探討 IronPDF,這是 Iron Software 提供的 Python PDF 生成套件。

PyYAML的主要功能

  1. 人類可讀格式:YAML 設計上容易閱讀和撰寫,非常適合複雜配置檔案和資料序列化。
  2. 完整的 YAML 1.1 支援:PyYAML 支援完整的 YAML 1.1 規範,包括 Unicode 支援和自訂資料型別。
  3. 與 Python 的整合:PyYAML 提供 Python 專用標籤,允許表達任意的 Python 物件,使其適用於各種應用。
  4. 錯誤處理:PyYAML 提供合理的錯誤訊息,在除錯過程中非常有用。

安裝

要安裝 YAML 套件,您可以使用 pip:

pip install pyyaml
pip install pyyaml
SHELL

基本用法

以下是一個簡單的範例,展示如何使用 PyYAML 載入和匯出 YAML 文件到和從任意 Python 物件。

import yaml

# Sample YAML data
yaml_data = """
name: John Doe
age: 30
children:
  - name: Jane Doe
    age: 10
  - name: Jim Doe
    age: 8
"""

# Load YAML data into a Python dictionary
data = yaml.safe_load(yaml_data)
print(data)

# Dump Python data back to formatted YAML
yaml_output = yaml.dump(data, default_flow_style=False)
print(yaml_output)
import yaml

# Sample YAML data
yaml_data = """
name: John Doe
age: 30
children:
  - name: Jane Doe
    age: 10
  - name: Jim Doe
    age: 8
"""

# Load YAML data into a Python dictionary
data = yaml.safe_load(yaml_data)
print(data)

# Dump Python data back to formatted YAML
yaml_output = yaml.dump(data, default_flow_style=False)
print(yaml_output)
PYTHON

輸出

PyYAML(開發者運作方式):圖1

進階特色

  1. 自訂資料型別:PyYAML 允許您定義自訂建構器和表示器以處理正規 YAML 格式的複雜資料型別。
import yaml

# Define a custom Python object
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Function to convert a Person object to a YAML representation
def person_representer(dumper, data):
    return dumper.represent_mapping('!Person', {'name': data.name, 'age': data.age})

# Function to create a Person object from YAML representation
def person_constructor(loader, node):
    values = loader.construct_mapping(node)
    return Person(**values)

# Register custom representer and constructor for Person
yaml.add_representer(Person, person_representer)
yaml.add_constructor('!Person', person_constructor)

# Object Serialization
person = Person(name='John Doe', age=30)
yaml_data = yaml.dump(person)
print(yaml_data)

# Deserialize YAML to a Person object
loaded_person = yaml.load(yaml_data, Loader=yaml.FullLoader)
print(loaded_person.name, loaded_person.age)
import yaml

# Define a custom Python object
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Function to convert a Person object to a YAML representation
def person_representer(dumper, data):
    return dumper.represent_mapping('!Person', {'name': data.name, 'age': data.age})

# Function to create a Person object from YAML representation
def person_constructor(loader, node):
    values = loader.construct_mapping(node)
    return Person(**values)

# Register custom representer and constructor for Person
yaml.add_representer(Person, person_representer)
yaml.add_constructor('!Person', person_constructor)

# Object Serialization
person = Person(name='John Doe', age=30)
yaml_data = yaml.dump(person)
print(yaml_data)

# Deserialize YAML to a Person object
loaded_person = yaml.load(yaml_data, Loader=yaml.FullLoader)
print(loaded_person.name, loaded_person.age)
PYTHON

輸出

PyYAML(開發者運作方式):圖2

  1. 處理大文件:PyYAML 通過流式載入和匯出,能高效處理多個 YAML 文件或大型 YAML 文件。
import yaml

# Load a large YAML file
with open('large_file.yaml', 'r') as file:
    data = yaml.safe_load(file)

# Dump data to a large YAML file
with open('output_file.yaml', 'w') as file:
    yaml.dump(data, file)
import yaml

# Load a large YAML file
with open('large_file.yaml', 'r') as file:
    data = yaml.safe_load(file)

# Dump data to a large YAML file
with open('output_file.yaml', 'w') as file:
    yaml.dump(data, file)
PYTHON

輸出

PyYAML(開發者運作方式):圖3

介紹 IronPDF

PyYAML(開發者運作方式):圖4

IronPDF是一個強大的Python程式庫,設計用於使用HTML、CSS、圖像和JavaScript來建立、編輯和簽署PDF。 它提供商業級的性能,並具備低記憶體佔用。 其主要功能包括:

  • HTML 到 PDF 轉換:將 HTML 文件、HTML 字串和 URL 轉換為 PDF。 例如,使用 Chrome PDF 轉換器將網頁渲染為 PDF。

  • 跨平台支援:相容各種 .NET 平台,包括 .NET Core、.NET Standard 和 .NET Framework。 它支援 Windows、Linux 和 macOS。

  • 編輯和簽署:設置屬性、通過密碼和權限新增安全性,並對 PDF 應用數位簽章。

  • 頁面範本和設定:使用頁眉、頁腳、頁碼和可調邊距自訂 PDF。 IronPDF 支援響應式佈局和自訂紙張尺寸。

  • 標準遵從:IronPDF 遵守 PDF 標準如 PDF/A 和 PDF/UA。 它支持UTF-8字元編碼並處理圖像、CSS、字體等資產。

使用 IronPDF 和 PyYAML 生成 PDF 文件

import yaml
import json
from ironpdf import *

# Apply your license key
License.LicenseKey = "your license"

# Sample YAML data
yaml_data = """
name: IronPDF User1
age: 25
children:
  - name: IronPDF User2
    age: 23
  - name: IronPDF User3
    age: 24
"""

# Load YAML data into Python structures
data = yaml.safe_load(yaml_data)
print(data)

# Dump Python data back to YAML
yaml_output = yaml.dump(data, default_flow_style=False)
print(yaml_output)

# Write YAML to File
with open('output_file.yaml', 'w') as file:
    yaml.dump(yaml_output, file)

# Write YAML data as JSON
with open('output_file.json', 'w') as json_file:
    json.dump(data, json_file)

# Read JSON and format with indentation for readability
output = json.dumps(json.load(open('output_file.json')), indent=2)
print(output)

# Create PDF renderer
renderer = ChromePdfRenderer()

# Create a PDF from HTML containing YAML data
content = "<h1>Awesome Iron PDF with PyYAML</h1>"
content += "<p>YAML data: " + yaml_output + "</p>"
pdf = renderer.RenderHtmlAsPdf(content)

# Save the PDF document to a file
pdf.SaveAs("awesome.pdf")
import yaml
import json
from ironpdf import *

# Apply your license key
License.LicenseKey = "your license"

# Sample YAML data
yaml_data = """
name: IronPDF User1
age: 25
children:
  - name: IronPDF User2
    age: 23
  - name: IronPDF User3
    age: 24
"""

# Load YAML data into Python structures
data = yaml.safe_load(yaml_data)
print(data)

# Dump Python data back to YAML
yaml_output = yaml.dump(data, default_flow_style=False)
print(yaml_output)

# Write YAML to File
with open('output_file.yaml', 'w') as file:
    yaml.dump(yaml_output, file)

# Write YAML data as JSON
with open('output_file.json', 'w') as json_file:
    json.dump(data, json_file)

# Read JSON and format with indentation for readability
output = json.dumps(json.load(open('output_file.json')), indent=2)
print(output)

# Create PDF renderer
renderer = ChromePdfRenderer()

# Create a PDF from HTML containing YAML data
content = "<h1>Awesome Iron PDF with PyYAML</h1>"
content += "<p>YAML data: " + yaml_output + "</p>"
pdf = renderer.RenderHtmlAsPdf(content)

# Save the PDF document to a file
pdf.SaveAs("awesome.pdf")
PYTHON

程式碼說明

  1. 導入:

    • 匯入必要的程式庫:yaml 用於 YAML 操作,json 用於 JSON 操作,ironpdf 用於 PDF 生成。
  2. 設置許可密鑰:

    • 設置 IronPDF 授權金鑰以合法和功能性存取程式庫。
  3. 範例 YAML 資料:

    • 定義範例 YAML 資料來展示 YAML 操作。
  4. YAML 操作:

    • 使用 yaml.safe_load() 將 YAML 資料轉換為 Python 物件以進行操作。
  5. 匯出至 YAML:

    • 使用 yaml.dump() 將 Python 物件轉換回 YAML 格式以輸出。
  6. 寫入文件:

    • 匯出 YAML 資料到 YAML 檔案和 JSON 資料到 JSON 檔案以供儲存或傳輸。
  7. 讀取 JSON 和格式化:

    • 從檔案中讀取 JSON 資料並使用 json.dumps() 格式化以提高可讀性。
  8. 使用 IronPDF 生成 PDF:

    • 使用 IronPDF 將 HTML 字串渲染為 PDF 文件,包括內嵌 YAML 資料。
  9. 保存 PDF:

    • 將生成的 PDF 保存到檔案系統中,展示程式化的 PDF 建立。

輸出

PyYAML(開發者運作方式):圖5

PDF

PyYAML(開發者運作方式):圖6

IronPDF 授權

IronPDF 在 Python 的授權金鑰下運行。 IronPDF for Python提供免費試用授權金鑰,以便使用者在購買前可以查看其豐富的功能。

將授權金鑰放在腳本開始處,以便在使用 IronPDF 套件之前使用:

from ironpdf import *

# Apply your license key
License.LicenseKey = "key"
from ironpdf import *

# Apply your license key
License.LicenseKey = "key"
PYTHON

結論

PyYAML 是一個強大且靈活的程式庫,用於在 Python 中處理 YAML。 它的人類可讀格式、完整的 YAML 1.1 支援和與 Python 的整合,使其成為配置檔案、資料序列化等的絕佳選擇。 無論您在處理簡單配置還是複雜的資料結構,PyYAML 提供了您需要的工具來有效地處理 YAML 資料。

IronPDF 是一個 Python 套件,便於將 HTML 內容轉換為 PDF 文件。 它為開發者提供了一個簡單的 API(ChromePdfRenderer),可從 HTML 生成高品質 PDF,支持現代的網頁標準如 CSS 和 JavaScript。 這使其成為一個高效的工具,可以直接從 Python 應用中動態建立和保存 PDF 文件。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話