Skip to main content
 首页 » 编程设计

python之是否可以使用 PyYAML 读取内部用 "YAML front matter" block 编写的文本文件

2025年05月04日9jillzhang

对不起,我对 YAML 和 PyYAML 知之甚少,但我很喜欢支持以与“Jekyll”(http://jekyllrb.com/docs/frontmatter/) 使用的风格相同的配置文件编写的想法,AFAIK 拥有这些“YAML Front Matter” block 对我来说看起来很酷很性感。
所以我在我的电脑上安装了 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 前端 block ?
还有什么我可以尝试使用 PyYAML 做的事情吗,或者我是否必须使用正则表达式编写自己的解析器?

非常感谢您的宝贵时间!

请您参考如下方法:

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