我有一个YAML文件:./YAML/simpleData.yml
- name: 'Somu'
age: 26
content:
- name: 'Neo'
age: 27
content: []
- name: 'Ari'
age: 26
content: []
我试图通过以下方式使用PyYAML解析它:
import yaml
# Creating objects directly with the YAML module:
print("Attempting Direct Object Load: ")
class Person:
def __init__(self, name, age, con):
self.name = name
self.age = hp
self.content = con
def __repr__(self):
return "%s(name=%r, hp=%r, sp=%r)" % (
self.__class__.__name__, self.name, self.age, self.content)
def printData(self):
print(self.name)
print(self.age)
if self.content:
for per in self.content:
print("-->", end="")
per.printData()
# Data load:
person_obj = None
data = ""
try:
with open('YAML/simpleData.yml') as source:
for line in source:
data += line
except Exception as err:
print("An exception occurred: " + str(err))
person_obj = yaml.load("""!!python/object:__main__.Person\n""" + data)
if not person_obj:
print("Data Loading Failed..! EXITING!!")
exit(1)
person_obj.printData()
我是Python的新手,因此无法确定我做错了什么,因为这个异常正在引发:
yaml.constructor.ConstructorError: expected a mapping node, but found sequence
in "<unicode string>", line 1, column 1:
!!python/object:__main__.Person
^
我该如何解决这个问题?
Attempting Direct Object Load:
Traceback (most recent call last):
File "/home/somu/Programming/python/HeadFirstPython/yamlIntro.py", line 106, in <module>
person_obj = yaml.load("""!!python/object:__main__.Person\n""" + data)
File "/home/somu/Programming/python/HeadFirstPython/venv/lib/python3.6/site-packages/yaml/__init__.py", line 72, in load
return loader.get_single_data()
File "/home/somu/Programming/python/HeadFirstPython/venv/lib/python3.6/site-packages/yaml/constructor.py", line 37, in get_single_data
return self.construct_document(node)
File "/home/somu/Programming/python/HeadFirstPython/venv/lib/python3.6/site-packages/yaml/constructor.py", line 46, in construct_document
for dummy in generator:
File "/home/somu/Programming/python/HeadFirstPython/venv/lib/python3.6/site-packages/yaml/constructor.py", line 578, in construct_python_object
state = self.construct_mapping(node, deep=deep)
File "/home/somu/Programming/python/HeadFirstPython/venv/lib/python3.6/site-packages/yaml/constructor.py", line 204, in construct_mapping
return super().construct_mapping(node, deep=deep)
File "/home/somu/Programming/python/HeadFirstPython/venv/lib/python3.6/site-packages/yaml/constructor.py", line 122, in construct_mapping
node.start_mark)
yaml.constructor.ConstructorError: expected a mapping node, but found sequence
in "<unicode string>", line 1, column 1:
!!python/object:__main__.Person
^
Process finished with exit code 1
答案 0 :(得分:1)
在根,c.q。您的文件的顶级,您有一个序列。其中第一个元素是映射,其中包含键值对name
:Somu
。
如果你想按照你所描述的方式使用PyYAML加载它,你应该删除每一行的前两个字符:
data += line[2:]
或在第一个短划线后插入!!python/object:__main__.Person
:
data = data.replace('- ', '- !!python/object:__main__.Person\n', 1)