ติดตั้ง PyYAML
python -m pip install pyyaml
Example1
import yaml dict1 = yaml.load(""" name: Vorlin Laruknuzum sex: Male class: Priest title: Acolyte hp: [32, 71] sp: [1, 13] gold: 423 inventory: - a Holy Book of Prayers (Words of Wisdom) - an Azure Potion of Cure Light Wounds - a Silver Wand of Wonder """) print(type(dict1)) print(dict1)
ผลการรัน จะมี Warning ว่า deprecated
YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details. """) <class 'dict'> {'name': 'Vorlin Laruknuzum', 'sex': 'Male', 'class': 'Priest', 'title': 'Acolyte', 'hp': [32, 71], 'sp': [1, 13], 'gold': 423, 'inventory': ['a Holy Book of Prayers (Words of Wisdom)', 'an Azure Potion of Cure Light Wounds', 'a Silver Wand of Wonder']}
นำผลลัพธ์มาจัด format จะได้ประมาณนี้
{ "name": "Vorlin Laruknuzum", "sex": "Male", "class": "Priest", "title": "Acolyte", "hp": [ 32, 71 ], "sp": [ 1, 13 ], "gold": 423, "inventory": [ "a Holy Book of Prayers (Words of Wisdom)", "an Azure Potion of Cure Light Wounds", "a Silver Wand of Wonder" ] }
Example2
import yaml st1 = yaml.dump({'name': "The Cloak 'Colluin'", 'depth': 5, 'rarity': 45,'weight': 10, 'cost': 50000, 'flags': ['INT', 'WIS', 'SPEED', 'STEALTH']}) print(type(st1)) print(st1)
ผลการรัน
<class 'str'> cost: 50000 depth: 5 flags: - INT - WIS - SPEED - STEALTH name: The Cloak 'Colluin' rarity: 45 weight: 10
Loading YAML
The function yaml.load
converts a YAML document to a Python object.
import yaml li1 = yaml.load(""" - Hesperiidae - Papilionidae - Apatelodidae - Epiplemidae """) print(type(li1)) print(li1)
YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details. """) <class 'list'> ['Hesperiidae', 'Papilionidae', 'Apatelodidae', 'Epiplemidae']
yaml.load
accepts a byte string, a Unicode string, an open binary file object, or an open text file object. A byte string or a file must be encoded with utf-8, utf-16-be or utf-16-le encoding. yaml.load
detects the encoding by checking the BOM (byte order mark) sequence at the beginning of the string/file. If no BOM is present, the utf-8 encoding is assumed.
import yaml dict1 = yaml.load(""" hello: สวัสดี """) print(type(dict1)) print(dict1)
<class 'dict'> {'hello': 'สวัสดี'}
สามารถอ่านจากไฟล์ได้ โดยถ้าจะให้ภาษาไทยอ่านถูกต้องให้ระบุ encoding
ให้ถูกด้วย
ใช้ safe_load()
จะไม่มี Warning ว่า deprecated
import yaml stream = open('document.yaml', 'r', encoding='utf-8') dict1 = yaml.safe_load(stream) print(type(dict1)) print(dict1)