【问题标题】:How would I parse 'Front Matter' with Python我将如何用 Python 解析“Front Matter”
【发布时间】:2014-09-06 06:50:53
【问题描述】:

我似乎没有任何关于如何使用 Python 解析“Front Matter”的示例。我有以下内容:

---
name: David
password: dwewwsadas
email: david@domain.com
websiteName: Website Name
websitePrefix: websiteprefix
websiteDomain: domain.com
action: create
---

我正在使用以下代码:

listing = os.listdir(path)
for infile in listing:
    stream = open(os.path.join(path, infile), 'r')
    docs = yaml.load_all(stream)
    for doc in docs:
        for k,v in doc.items():
            print k, "->", v
    print "\n",

由于第二组---,我不断收到错误

【问题讨论】:

    标签: python yaml


    【解决方案1】:

    我知道这是一个老问题,但我刚刚遇到同样的问题并使用了python-frontmatter。以下是向Front matter添加新变量的示例:

    import frontmatter
    import io
    from os.path import basename, splitext
    import glob
    
    # Where are the files to modify
    path = "en/*.markdown"
    
    # Loop through all files
    for fname in glob.glob(path):
        with io.open(fname, 'r') as f:
            # Parse file's front matter
            post = frontmatter.load(f)
            if post.get('author') == None:
                post['author'] = "alex"
                # Save the modified file
                newfile = io.open(fname, 'w', encoding='utf8')
                frontmatter.dump(post, newfile)
                newfile.close()
    

    来源How to parse frontmatter with python

    【讨论】:

      【解决方案2】:

      --- 启动新文档,这会导致您的第二个文档为空,而 doc 在第二部分为 None。您遍历 doc 的键、值对,就好像每个 doc 都是 Python dict 或等效类型,但 None 不是,所以您应该在循环中测试它(当然有有多种方法可以做到这一点,如果doc 不是dict,该怎么办):

      ....
      for doc in yaml.load_all(stream):
          if hasattr(doc, 'items'):
              for k, v in doc.items():
                  print k, "->", v
          else:
              print doc
      

      【讨论】:

        猜你喜欢
        • 2011-10-26
        • 1970-01-01
        • 2019-01-27
        • 1970-01-01
        • 2015-12-24
        • 2015-06-29
        • 1970-01-01
        • 2015-11-23
        • 1970-01-01
        相关资源
        最近更新 更多