将输出写入 Python 中的文件

Write output into a file in Python

我有抓取功能,可以返回以下形式的内容:

{'tagged': ['The Doors', 'Jim Morrison', 'Ray Manzarek', 'Robbie Krieger', 'John Densmore'], 'iframe': <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="281" id="youtube_iframe" src="https://www.youtube.com/embed/eqgXGMAS__M?feature=oembed&amp;enablejsapi=1&amp;origin=https://safe.txmblr.com&amp;wmode=opaque" width="500"></iframe>, 'date': '2020-01-13'}

我想要的输出是将其保存在 markdown 文件中,格式如下:

---
title:  # this one is grabbed from url name
date: 2020-01-13
---
tagged: [[The Doors]], [[Jim Morrison]], [[Ray Manzarek]], [[Robbie Krieger]], [[John Densmore]]
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="281" id="youtube_iframe" src="https://www.youtube.com/embed/eqgXGMAS__M?feature=oembed&amp;enablejsapi=1&amp;origin=https://safe.txmblr.com&amp;wmode=opaque" width="500"></iframe>

在我必须添加日期之前,我使用的代码如下:

def write_posts(content, url, save_path):
    note_file_name = url.split('/')[4] + '.md'
    with open(save_path/note_file_name, 'w', encoding='utf-8') as f:
        f.write(f"---\n"
                f"title: '{re.sub('[^0-9]', '', f.name)}'\n"
                f"---\n")
        for key, value in content.items():
            if type(value) is list:
                f.write(f"{key}: [[{']], [['.join(value)}]]")
            else:
                f.write(f"\n{value}")
    f.close()

但它不适用于日期,它只是将其添加到底部。 我尝试将最后一行更改为:

        for key, value in content.items():
            if type(value) is list:
                f.write(f"{key}: [[{']], [['.join(value)}]]")
            elif type(key) == "iframe":
                    f.write(f"\n{value}")
                else:
                    f.close()

但它完全省略了 iframe 和日期。

我认为您的字符串的 iframe 字段不是有效的 JSON 格式。

如果由您来解决,我会推荐。

但是,我认为以下函数在接收 json 作为参数时工作正常。

def write_posts(content, url, save_path):
    note_file_name = url.split('/')[3] + '.md'


    title_line=f'title: {url}'
    date_line=f'date: {content["date"]}'
    separator='---'
    tagged_formated=", ".join([  str([[i]]) for i in content["tagged"]  ])
    tagged_line=f'tagged: {tagged_formated}'
    iframe_line=content["iframe"]
    text=title_line+"\n"+date_line+"\n"+separator+"\n"+tagged_line+"\n"+iframe_line

    with open(save_path+"/"+note_file_name, 'w', encoding='utf-8') as f:
        f.write(text)
    f.close()


json={'tagged': ['The Doors', 'Jim Morrison', 'Ray Manzarek', 'Robbie Krieger', 'John Densmore'], 'iframe':'<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="281" id="youtube_iframe" src="https://www.youtube.com/embed/eqgXGMAS__M?feature=oembed&amp;enablejsapi=1&amp;origin=https://safe.txmblr.com&amp;wmode=opaque" width="500"></iframe>', 'date': '2020-01-13'}
url="https://www.hello.com/myhome.html"
path_dir= "C:/Users/USERNAME/Desktop" 
write_posts(json, url,path_dir)

希望对您有所帮助!

多亏了 Luis 的回答,我明白了我想要/应该做什么才能让它发挥作用。 现在代码输出我想要它做的事情:

def write_posts(content, url, save_path):
    note_file_name = url.split('/')[4] + '.md'
    date = content.get('date')
    iframe = content.get('iframe')

    with open(save_path/note_file_name, 'w', encoding='utf-8') as f:
        f.write(f"---\n"
                f"title: '{re.sub('[^0-9]', '', f.name)}'\n"
                f"date: {date}\n"
                f"---\n")
        for key, value in content.items():
            if type(value) is list:
                f.write(f"{key}: [[{']], [['.join(value)}]]")
            else:
                f.write(f"\n{iframe}")
                break
        f.close()

谢谢!