フッターコンテンツにスキップ
PYTHONヘルプ

PyYAML(開発者向けのしくみ)

PyYAMLは、YAMLパーサー兼エミッタとして機能するPythonライブラリです。 YAML(YAML Ain’t Markup Language)は、Pythonアプリケーションとよく統合される、人間に読みやすいデータシリアル化フォーマットで、優れたエラーサポート、強力な拡張APIなどを備えています。 YAMLは、設定ファイルや異なるデータ構造を持つ言語間のデータ交換に使われることが多く、人間の可読性を念頭に置いています。 Later in this article, we will look into IronPDF, a PDF-generation Python package from Iron Software.

PyYAMLの主要な機能

  1. 人間に読みやすい形式: YAMLは、読み書きが容易になるように設計されており、複雑な設定ファイルやデータシリアル化に最適です。
  2. 完全なYAML 1.1サポート: PyYAMLは、Unicodeサポートやカスタムデータタイプを含む、YAML 1.1の完全な仕様をサポートしています。
  3. Pythonとの統合: PyYAMLは、任意のPythonオブジェクトの表現を可能にするPython固有のタグを提供し、さまざまなアプリケーションで多用途に使用できます。
  4. エラー処理: PyYAMLは、デバッグ中に非常に役立つ、合理的なエラーメッセージを提供します。

インストール

YAMLパッケージをインストールするには、pipを使用できます:

pip install pyyaml
pip install pyyaml
SHELL

基本的な使い方

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)
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は、HTML、CSS、画像、JavaScriptを使用してPDFを作成、編集、署名するために設計された強力なPythonライブラリです。 低メモリフットプリントながら商用グレードのパフォーマンスを備えています。 主な機能は以下のとおりです:

  • HTMLからPDFへの変換: HTMLファイル、HTML文字列、URLをPDFに変換します。 たとえば、Chrome PDFレンダラーを使用してウェブページをPDFとしてレンダリングします。

  • クロスプラットフォームサポート: .NET Core、.NET Standard、および.NET Frameworkを含む様々な.NETプラットフォームと互換性があります。 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は、HTMLコンテンツをPDFドキュメントに変換するPythonパッケージです。 現代のウェブ標準であるCSSやJavaScriptを含むHTMLから高品質のPDFを生成するためのシンプルなAPI(ChromePdfRenderer)を提供します。 これにより、Pythonアプリケーションから直接PDFドキュメントを動的に作成および保存するための効果的なツールとなっています。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。