抱歉,我对YAML和PyYAML知之甚少,但是我爱上了支持以“ Jekyll”(http://jekyllrb.com/docs/frontmatter/)所用的相同样式编写的配置文件的想法,而AFAIK拥有这些“ YAML前端问题”对我来说看起来很酷很性感的方块。
因此,我在计算机上安装了PyYAML,并使用以下文本块编写了一个小文件:

---
First Name: John
Second Name: Doe
Born: Yes
---

Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.


然后,我尝试使用以下代码通过Python 3.4和PyYAML读取此文本文件:

import yaml

stream = open("test.yaml")
a = stream.read()
b = yaml.load(a)


但是很明显,它不起作用,Python显示此错误消息:

Traceback (most recent call last):
  File "<pyshell#62>", line 1, in <module>
    b = yaml.load(a)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/yaml/__init__.py", line 72, in load
    return loader.get_single_data()
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/yaml/constructor.py", line 35, in get_single_data
    node = self.get_single_node()
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/yaml/composer.py", line 43, in get_single_node
    event.start_mark)
yaml.composer.ComposerError: expected a single document in the stream
  in "<unicode string>", line 2, column 1:
    First Name: John
    ^
but found another document
  in "<unicode string>", line 5, column 1:
    ---
    ^


请问你能帮帮我吗?
我是否以错误的方式编写了代码,或者这意味着PyYAML无法处理YAML前端问题块?
我还可以尝试使用PyYAML做其他事情,还是必须使用regex编写自己的解析器?

非常感谢您的宝贵时间 !

最佳答案

Python yaml库不支持读取文档中嵌入的yaml。这是一个提取yaml文本的实用程序函数,因此您可以在读取文件的其余部分之前对其进行解析:

#!/usr/bin/python2.7

import yaml
import sys

def get_yaml(f):
  pointer = f.tell()
  if f.readline() != '---\n':
    f.seek(pointer)
    return ''
  readline = iter(f.readline, '')
  readline = iter(readline.next, '---\n')
  return ''.join(readline)


for filename in sys.argv[1:]:
  with open(filename) as f:
    config = yaml.load(get_yaml(f))
    text = f.read()
    print "TEXT from", filename
    print text
    print "CONFIG from", filename
    print config

关于python - 是否可以使用PyYAML读取内部带有“YAML前题”块的文本文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25814568/

10-12 23:10