py自动化脚本实现去除hexo标签插件语法
[TOC]
需求
鱼和熊掌不可兼得,当采用typora
编写md文档时,typora等其他软件是不支持hexo的插件语法的,故而不会实时渲染的.只会显示源代码: 例如
源码
{% note danger, note error/danger %}
{% note success, note done/success %}
当同步发表到CSDN等其他博客时,会把源代码显示出来,显得非常不美观,且含有乱码.
故而写一个自动化脚本去除含有 hexo 语法的 内容, 尝试还源一个纯净的md文件
代码
code
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @Author: float311@163.com; sizaif2000@163.com
# @Description: 将hexo博客修改为csdn可以使用的格式
# @Date 2021/8/8 17:59
# @Update 2021-08-09 10:17:50
# @note:
# 已知bug:
# 1. hexo语法不能与文本混用,即处在一行中, 例如: 带 {% u 下划线 %} 的文本 ; 会导致 文本内容丢失
# 2. 代码框中内容也会被处理
import sys,re
def matchstring(line):
# radio, checkout note
matchradio = re.search(r'{% [rcn].*',line,re.I)
if matchradio:
return re.sub(
r'%}',
"",
','.join(line.split(',')[1:])
).replace(" ", "")
# floding timeline, tab end
matchall = re.search(r'{% [fte].*',line,re.I)
if matchall:
# 全部丢弃
return None
# link
matchlink = re.search(r'{% link .*',line,re.I)
if matchlink:
temp = line.split(',')
line = "["+temp[0].split(' ')[-1]+"]("+re.sub(r'%}',"",temp[-1])+")"
return line.strip()
# audio,video
matchaudio = re.search(r'{% [av].*',line,re.I)
if matchaudio:
return line.split(' ')[-2].replace(" ","")
# <!--类
matchall2 = line.find("<!--")
if matchall2:
return None
def modify(original, result):
"""
根据hexo MD文件生成CSDN博客适用的MD文件
:param original: 源文件
:param result: 新文件
"""
content = ""
with open(original, "r+", encoding="UTF-8") as o:
for line in o.readlines():
if line.find("{%") == -1 and line.find("<!--"):
content += line
else:
line = matchstring(line)
if line is not None:
content += line
with open(result, "w+", encoding="UTF-8") as n:
n.write(content)
if __name__ == '__main__':
original_md = sys.argv[1] + ".md"
result_md = sys.argv[2] + ".md"
modify(original_md, result_md)
使用方法
# 文件名不需要带md
$ py main 源文件 输出文件
已知bug
radio,checkout,note 文本内容中不能含有’,'(逗号), 会导致分割数据丢失- hexo语法不能与文本混用,即处在一行中, 例如: 带
{% u 下划线 %}的文本
; 会导致文本内容丢失 - 代码框中的内容也会被处理
上面的情况暂时需要手动处理