PyYAML(開發人員工作原理)
PyYAML 是一個Python程式庫,作為一個YAML解析器和發射器運行。 YAML(YAML不是標記語言),是一種人類可讀的數據序列化格式,與Python應用程式整合良好,具有出色的錯誤支援功能、完備的擴展API等更多優點。 YAML經常用於配置文件和在具有不同數據結構的語言間進行數據交換,著重於人類可讀性。 在本文的後面,我們將研究來自Iron Software的PDF生成Python套件IronPDF。
PyYAML的關鍵功能
- 人類可讀格式:YAML的設計是為了易於讀寫,非常適合複雜的配置文件和數據序列化。
- 完整的YAML 1.1支援:PyYAML支援完整的YAML 1.1規範,包括Unicode支援和自定義數據類型。
- 與Python整合:PyYAML提供特定於Python的標籤,允許表示任意Python對象,使其在各種應用中非常靈活。
- 錯誤處理:PyYAML提供合理的錯誤信息,這對於調試非常有幫助。
安裝
要安裝YAML程式包,您可以使用pip:
pip install pyyamlpip install pyyaml基本用法
這是一個簡單的範例,展示如何使用PyYAML從任意Python對象加載和轉儲YAML文檔。
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)輸出

進階功能
- 自定義數據類型: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)輸出

- 處理大型文件: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)輸出
![]()
介紹 IronPDF

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")代碼解釋
導入:
- 導入必要的程式庫:
yaml用於YAML操作,json用於JSON操作,ironpdf用於PDF生成。
- 導入必要的程式庫:
設置授權金鑰:
- 設置IronPDF授權金鑰,以合法和功能性存取程式庫。
範例YAML數據:
- 定義範例YAML數據以演示YAML操作。
YAML操作:
- 使用
yaml.safe_load()將YAML數據轉換為Python對象以進行操作。
- 使用
轉儲到YAML:
- 使用
yaml.dump()將Python對象轉換回YAML格式以進行輸出。
- 使用
寫入文件:
- 將YAML數據匯出為YAML文件,並將JSON數據匯出為JSON文件,用於存儲或傳輸。
讀取JSON並格式化:
- 從文件中讀取JSON數據,並使用
json.dumps()進行可讀性格式化。
- 從文件中讀取JSON數據,並使用
使用IronPDF生成PDF:
- 使用IronPDF將HTML字符串渲染成包含嵌入YAML資料的PDF文檔。
保存PDF:
- 將生成的PDF保存到文件系統中,展示程式化的PDF創建。
輸出


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"結論
PyYAML是一個強大而靈活的程式庫,用於在Python中處理YAML。 其可讀性格式、完整的YAML 1.1支援及與Python的整合,讓它成為配置文件、數據序列化等的理想選擇。 無論您正在處理簡單配置還是複雜數據結構,PyYAML都提供了有效處理YAML數據的工具。
IronPDF是一個Python套件,使HTML內容轉換為PDF文檔變得容易。 它提供了一個直接的API(ChromePdfRenderer)供開發者從HTML生成高品質的PDF,其中包括支援現代網頁標準如CSS和JavaScript。 這使得它成為從Python應用程式中動態創建和保存PDF文件的有效工具。










