问题描述:在我用插件从优快云下载markdown文件后发现,我们的图片通常是用url来表示,这使得很不方便(如果这个文章消失了我们就不能看图片了)。这时我们可以使用我的这python文件
在此之前为了方便,可以用全局替换,将"在这里插入图片描述"修改为"&"
这样我们就可以直接正则匹配"&"
python文件:
import re
from datetime import datetime
import requests
# 读取txt文件内容
with open('E:\\temp\\JUC并发编程.md', 'r', encoding='utf-8') as f:
content = f.read()
# 使用正则表达式匹配被()覆盖的图片url
pattern = r'\&\]\((.*?)\)'
urls = re.findall(pattern, content)
print(urls)
# 下载图片到本地并替换文本中对应的url
for i, url in enumerate(urls):
response = requests.get(url)
now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S-%f')
filename = f'E:\\temp\\image_{i}_{now}.jpg'
with open(filename, 'wb') as f:
f.write(response.content)
# 替换文本中对应的url为本地图片路径
content = content.replace(url, filename)
# 将替换后的文本写入新文件中
with open('E:\\temp\\JUC并发编程_with_images.md', 'w', encoding='utf-8') as f:
f.write(content)
成功!