在Python中输出Markdown格式文件可以通过以下几种方法实现:
使用第三方库
例如,使用`aspose.words`库可以将PDF文件转换为Markdown格式。
import aspose.words as aw
doc = aw.Document('pdf文件路径\xxx.pdf')
doc.save('Output.md')
使用HTML转Markdown工具
可以使用`html2text`库将HTML内容转换为Markdown格式。
import html2text
def convert_html2md(src_html, target_md):
with open(src_html, 'r', encoding='utf-8') as f:
html = f.read()
markdown = html2text.html2text(html)
with open(target_md, 'w', encoding='utf-8') as f:
f.write(markdown)
批量转换HTML文件
可以编写一个脚本来遍历指定目录下的所有HTML文件,并将它们转换为Markdown格式。
import os
def batch_convert(root_path):
for root, dirs, files in os.walk(root_path):
for filename in files:
if filename.endswith('.html'):
file_path = os.path.join(root, filename)
target_md = os.path.join(root, filename.replace('.html', '.md'))
if not os.path.exists(target_md):
convert_html2md(file_path, target_md)
print(f'{target_md} 已生成')
抓取网页内容并保存为Markdown
可以使用`requests`和`BeautifulSoup`库抓取网页内容,然后将其保存为Markdown格式。
import requests
from bs4 import BeautifulSoup
def download_article(article_url):
response = requests.get(article_url)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
title = soup.select_one('.title-article').text
content = soup.select('.article').text
with open('output.md', 'w', encoding='utf-8') as f:
f.write(f" {title}\n\n{content}")
以上方法可以帮助你在Python中输出Markdown格式文件。请根据你的具体需求选择合适的方法