2019-06-11 16:26:24 +08:00
|
|
|
''' mbinary
|
|
|
|
#########################################################################
|
|
|
|
# File : codecogs.py
|
|
|
|
# Author: mbinary
|
|
|
|
# Mail: zhuheqin1@gmail.com
|
|
|
|
# Blog: https://mbinary.xyz
|
|
|
|
# Github: https://github.com/mbinary
|
|
|
|
# Created Time: 2019-04-16 09:41
|
|
|
|
# Description:
|
|
|
|
#########################################################################
|
|
|
|
'''
|
2019-03-18 00:46:56 +08:00
|
|
|
import os
|
|
|
|
import re
|
|
|
|
import sys
|
|
|
|
from translate import Translator as TR
|
|
|
|
|
2020-04-15 12:28:20 +08:00
|
|
|
FORMULA = re.compile(r'\${1,2}(?P<formula>.+?)\${1,2}', re.DOTALL)
|
2019-03-18 00:46:56 +08:00
|
|
|
Chinese = re.compile(u"(?P<chinese>[\u4e00-\u9fa5]+)")
|
|
|
|
API = 'https://latex.codecogs.com/gif.latex?'
|
2020-04-15 12:28:20 +08:00
|
|
|
|
|
|
|
|
2019-03-18 00:46:56 +08:00
|
|
|
def codecog(f):
|
|
|
|
if os.path.exists(f) and f.endswith('.md'):
|
|
|
|
with open(f) as fp:
|
|
|
|
txt = fp.read()
|
2020-04-15 12:28:20 +08:00
|
|
|
with open(f, 'w') as fp:
|
|
|
|
fp.write(re.sub(FORMULA, covert, txt))
|
2019-03-18 00:46:56 +08:00
|
|
|
else:
|
2020-04-15 12:28:20 +08:00
|
|
|
s = re.sub(FORMULA, covert, f)
|
2019-03-18 00:46:56 +08:00
|
|
|
print(s)
|
2020-04-15 12:28:20 +08:00
|
|
|
|
|
|
|
|
2019-03-18 00:46:56 +08:00
|
|
|
def covert(matched):
|
|
|
|
s = matched.group('formula').strip('$ ')
|
2020-04-15 12:28:20 +08:00
|
|
|
s = re.sub(Chinese, zh2en, s)
|
|
|
|
s = re.sub(r'\r+|\n+|\\n', ' ', s)
|
|
|
|
s = re.sub(' +', '&space;', s)
|
|
|
|
return '![]({})'.format(API+s)
|
|
|
|
|
|
|
|
|
2019-03-18 00:46:56 +08:00
|
|
|
def zh2en(txt):
|
|
|
|
s = txt.group('chinese').strip()
|
2020-04-15 12:28:20 +08:00
|
|
|
tran = TR(to_lang='en', from_lang='zh')
|
2019-03-18 00:46:56 +08:00
|
|
|
en = tran.translate(s)
|
2020-04-15 12:28:20 +08:00
|
|
|
return re.sub(' +', '-', en)
|
|
|
|
|
2019-03-18 00:46:56 +08:00
|
|
|
|
|
|
|
def handle(path):
|
|
|
|
if os.path.isdir(path):
|
2020-04-15 12:28:20 +08:00
|
|
|
for p, ds, fs in os.walk(path):
|
2019-03-18 00:46:56 +08:00
|
|
|
for f in fs:
|
|
|
|
if f.endswith('.md'):
|
2020-04-15 12:28:20 +08:00
|
|
|
codecog(os.path.join(p, f))
|
2019-03-18 00:46:56 +08:00
|
|
|
else:
|
|
|
|
codecog(path)
|
|
|
|
|
2020-04-15 12:28:20 +08:00
|
|
|
|
2019-03-18 00:46:56 +08:00
|
|
|
if __name__ == '__main__':
|
|
|
|
args = sys.argv[1:]
|
|
|
|
if not args:
|
|
|
|
s = input('Input a file: ')
|
|
|
|
args.append(s)
|
|
|
|
for f in args:
|
|
|
|
handle(f)
|