【问题标题】:How to Use Python Script to Convert HTML to Markdown in Batch [duplicate]如何使用 Python 脚本将 HTML 批量转换为 Markdown [重复]
【发布时间】:2021-03-18 16:53:16
【问题描述】:

我正在尝试将目录下的所有 .html 文件转换为 Markdown。经过一番谷歌搜索后,我发现了一个名为 html2text 的 Pypi 脚本。

然后我写了一个代码块,可以一次将一个.html转换成.md。

import html2text as ht
import os
import sys

from pathlib import Path

text_maker = ht.HTML2Text()

with open('myHtmlFilePath.html','r',encoding='UTF-8') as f:
    htmlpage = f.read()

text = text_maker.handle(htmlpage)

with open('myMarkdownFileName.md','w') as f:
    f.write(text)

有没有可能我可以将此代码块包装在一个循环中,以便它可以将任何文件扩展名为 .html 的文件转换为给定目录下的 .md?

【问题讨论】:

  • this 有帮助吗?
  • 作为 Python 的新手,我需要使用我的面条来弄清楚如何将您的引用集成到我的代码中。但无论如何,谢谢,这绝对是有用的,虽然我还没有弄清楚如何。

标签: python html markdown


【解决方案1】:

如果你使用 linux 你可以使用 find 命令

Linux

import os

dir = "."

for file in os.popen("find " + dir).read().splitlines():
    if file.endswith(".html"):
        print(file)

窗口

import os

dir = "."

for i in os.walk(dir):
    for i2 in i[2]:
        if i2.endswith(".html"):
            print(i[0] + "/" + i2)

【讨论】:

  • 非常感谢。我在Win10中编写了我的脚本。 Win10如何实现你的代码?
  • @eyal 最好坚持使用更便携(跨平台)的解决方案,正如我在上面发布的链接中所建议的那样。
  • 呃,请不要为此掏腰包。 Python 完全能够迭代文件本身。对于初学者,请参阅the link provided by costaparas in the comments above
猜你喜欢
  • 1970-01-01
  • 2018-08-02
  • 2018-04-13
  • 2011-10-28
  • 1970-01-01
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多