Last active
July 6, 2017 13:20
-
-
Save kaminomisosiru/6cbc43c2d05cd84c3511303836321d61 to your computer and use it in GitHub Desktop.
はてなブログ用のmarkdownで$$で囲まれた\、^、_をエスケープするためのスクリプト(正しく動いているかは不明)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
# -*- coding:utf-8 -*- | |
# 参考:http://d.hatena.ne.jp/greennoah/20090216/1234784592 | |
import re | |
import sys | |
import os | |
# $...$で囲まれたインライン数式用の置換 | |
def inline_replace(line): | |
line = re.sub(r'\\(?=.*\$)', r'\\\\', line) | |
line = re.sub(r'\^(?=.*\$)', r'\^', line) | |
line = re.sub(r'_(?=.*\$)', r'\_', line) | |
return line | |
# $$...$$で囲まれたブロック数式用の置換 | |
def block_replace(line): | |
line = re.sub(r'\\', r'\\\\', line) | |
line = re.sub(r'\^', r'\^', line) | |
line = re.sub(r'_', r'\_', line) | |
return line | |
if len(sys.argv) < 1: | |
print('Please input filename') | |
sys.exit(0) | |
read_file = None | |
write_file = None | |
block_flag = False | |
temp_file = sys.argv[1].replace('.md', '')+'_convert.md' | |
try: | |
read_file = open(sys.argv[1], 'r') | |
write_file = open(temp_file, 'w') | |
for line in read_file: | |
if line.strip() == '$$': | |
block_flag = not(block_flag) | |
if block_flag: | |
line = block_replace(line) | |
else: | |
line = inline_replace(line) | |
write_file.write(line) | |
finally: | |
read_file.close() | |
write_file.close() | |
# if os.path.isfile(sys.argv[1]) and os.path.isfile(temp_file): | |
# os.remove(sys.argv[1]) | |
# os.rename(temp_file, sys.argv[1]) | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment