Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

title: Markdown et Python

Suite des utilitaires utilisés pour générer ce site.

J’ai une arborescence de fichiers markdown que je transforme en fichiers HTML. Je commence donc par les récupérer :

:::python
def each_markdown_from(source_dir, file_name='index.md'):
    """Walk across the `source_dir` and return the md file path."""
    for root, dirnames, filenames in os.walk(source_dir):
        for filename in fnmatch.filter(filenames, file_name):
            yield os.path.join(root, filename)

Ce petit utilitaire parcoure un dossier et retourne le chemin d’accès s’il contient index.md. J’ai une seconde fonction qui me permet de parser un fichier markdown et de compiler le contenu avec ses méta-données :

:::python
def parse_markdown(file_path, extensions=None):
    """Parse an md file and returns its converted content and metadata."""
    if extensions is None:
        extensions = ['meta', 'codehilite']
    parser = markdown.Markdown(extensions=extensions)
    with codecs.open(file_path, 'r', 'utf-8') as source:
        content = parser.convert(source.read())
        return content, hasattr(parser, 'Meta') and parser.Meta or None

En combinant les deux, on obtient la boucle suivante :

:::python
for file_path in each_markdown_from(POSTS_PATH):
    content, metadata = parse_markdown(file_path)

Dans un prochain épisode, on verra comment utiliser les namedtuples à bon escient.