MathType的公式Latex到Katex转换程序
【摘要】
■ 前言
在 如何高效优雅的在CSDN中输入公式 博文中介绍了利用MathType输入数学公式的方法。本文就是将其中相关的Python程序给出。以方便拷贝使用。
01程序
...
■ 前言
在 如何高效优雅的在CSDN中输入公式 博文中介绍了利用MathType输入数学公式的方法。本文就是将其中相关的Python程序给出。以方便拷贝使用。
01程序
1.mt2csdn
本程序是将MATHTYPE中的带有矩阵符合的公式转换为CSDN中的Katex的格式。
#!/usr/local/bin/python
# -*- coding: gbk -*-
#============================================================
# MT2CSDN.PY -- by Dr. ZhuoQing 2020-06-07
#
# Note:
#============================================================
from head import *
csdn_title = '写文章-CSDN博客'
#------------------------------------------------------------
if len(sys.argv) == 1: exit()
pastestr = sys.argv[1]
pastestr = pastestr.replace('`', ' ')
#------------------------------------------------------------
startmark = pastestr.find('$$')
if startmark < 0:
printf("No $$ presents for latex.\a")
exit
endmark = pastestr[startmark+2:].find('$$')
if endmark < 0:
printf("No end $$ presents for latex.\a")
exit
printf(pastestr)
#printf(len(pastestr))
#printf(startmark, endmark)
pastestr = pastestr[startmark+2:startmark+2+endmark].split('\\cr')
#printf(pastestr)
#------------------------------------------------------------
stringsect = [s.strip(' ') for s in pastestr]
if stringsect[0] == '\\eqalign{':
stringsect = stringsect[1:-1]
if stringsect[-1] == '}':
stringsect = stringsect[0:-1]
printf(stringsect)
#------------------------------------------------------------
emptystr = 0
mathstr = ''
sectnum = len(stringsect)
matrixbeginflag = 0
for id,s in enumerate(stringsect):
s=s.replace('\\left[', '\\begin{bmatrix}')
s=s.replace('\\right]', '\\end{bmatrix}')
s=s.replace('\\eqalign{ ', "")
if s == '}': continue
if s.find('} } ') >= 0:
matrixbeginflag = 0
s=s.replace('} }', '\\end{matrix}')
matrixbegin = s.find('{\\matrix{')
if matrixbegin >= 0:
shead = s[0:matrixbegin]
# smatrix = '&'.join([ss for ss in s[matrixbegin+9:].split(' ') if len(ss) > 0])
smatrix = s[matrixbegin+9:]
s = '%s \\begin{matrix} %s'%(shead, smatrix)
matrixbeginflag = 1
else:
# if matrixbeginflag == 1:
# s = '&'.join([ss for ss in s.split(' ') if len(ss) > 0])
pass
if len(s) == 0: emptystr = emptystr + 1
else:
mathstr = mathstr + s
if id < sectnum - 1 and matrixbeginflag == 1:
if len(stringsect[id + 1]) > 0:
mathstr = mathstr + '\\\\'
if matrixbeginflag == 0:
if id < sectnum - 1:
mathstr = mathstr + " $$$$ "
#------------------------------------------------------------
if emptystr > 1:
insertstr = '$%s$'%mathstr
else: insertstr = '$$%s$$\r\n'%mathstr
#------------------------------------------------------------
clipboard.copy(insertstr)
tspsendwindowkey(csdn_title, 'v', control=1, noreturn=1)
clipboard.copy('')
#tspfocuswindow(csdn_title)
#------------------------------------------------------------
# END OF FILE : MT2CSDN.PY
#============================================================
2.mpc
将MATHTYPE中的公式按照图片格式插入到CSDN。
#!/usr/local/bin/python
# -*- coding: gbk -*-
#============================================================
# MTPIC2CSDN.PY -- by Dr. ZhuoQing 2020-06-17
#
# Note:
#============================================================
from head import *
import matplotlib.image as mpimg
from PIL import Image, ImageFont, ImageDraw
from io import BytesIO
import win32clipboard
#------------------------------------------------------------
csdn_window = '写文章-CSDN博客'
#------------------------------------------------------------
def send_to_clipboard(clip_type, data):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(clip_type, data)
win32clipboard.CloseClipboard()
#------------------------------------------------------------
mathtype_title = 'MathType'
tempdir = r'd:\temp'
if os.path.isdir(tempdir) == False:
printf("ERROR: The temporal directory d:\\temp is not existed.")
exit()
#------------------------------------------------------------
mathtypepic = os.path.join(tempdir, 'MATHTYPE.BMP')
mtrect = tspgetwindowrect(mathtype_title)
#printf(mtrect)
if mtrect[2] - mtrect[0] == 0 or\
mtrect[3] - mtrect[1] == 0:
printf("ERROR: MathType window does not exist!")
exit()
#------------------------------------------------------------
tspsavescreenrect(mathtypepic, mtrect)
img = mpimg.imread(mathtypepic)
r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]
#gray = 0.2989*r + 0.5870*g + 0.1140*b
gray = r/3 + g/3 + g/3
#printf(shape(gray))
centerx = shape(gray)[1] - 30
centery = shape(gray)[0] - 45
horzline = gray[centery, 0:centerx][::-1]
vertline = gray[0:centery, centerx][::-1]
#------------------------------------------------------------
marginleft = -1
marginright = centerx
margintop = -1
marginbottom = centery
for id,s in enumerate(horzline):
if s < 254:
marginleft = len(horzline) - id
break
for id,s in enumerate(vertline):
if s < 254:
margintop = len(vertline) - id
break
if marginleft == -1 or marginright == -1 or margintop == -1 or marginbottom == -1:
printf("ERROR: MathType has no margin.")
exit()
#printf("Margin: %d,%d,%d,%d"%(marginleft, margintop, marginright, marginbottom))
#------------------------------------------------------------
rectleft = -1
recttop = -1
rectright = -1
rectbottom = -1
n = 9
checkright = int(shape(gray)[1] * 9 / 10)
if len(sys.argv) > 2:
if sys.argv[2].isnumeric():
n = int(sys.argv[2])
if n < 2: n = 2
checkright = int(shape(gray)[1]*(n - 1) / n)
#------------------------------------------------------------
for i in range(margintop, marginbottom+1):
if list(gray[i, marginleft:checkright] < 250).count(True) > 0:
if recttop == -1:
recttop = i
rectbottom = i
for i in range(marginleft, marginright+1):
if list(gray[recttop:rectbottom+1, i] < 250).count(True) > 0:
if rectleft == -1:
rectleft = i
rectright = i
if rectleft < 0 or recttop < 0 or rectright < 0 or rectbottom < 0:
printf("ERROR: No find the formular.")
exit()
#------------------------------------------------------------
fillrectwidth = 0
sideflag = 0
sidecolor = (0,0,128)
#------------------------------------------------------------
formularstr = ''
if len(sys.argv) > 1:
if sys.argv[1][0] != '#' and sys.argv[1][0] != '.':
rectright = marginright
formularstr = sys.argv[1]
fillrectwidth = rectleft
rectleft = 0
else:
if sys.argv[1] != '..':
rectwidth = rectright + 1 - rectleft
rectcenter = int((rectleft + rectright) / 2)
totalwidth = marginright + 1 - rectleft
fillrectwidth = rectleft
rectleft = rectcenter - int(totalwidth / 2)
fillrectwidth = fillrectwidth - rectleft
rectright = rectleft + totalwidth
if len(sys.argv[1]) > 1:
formularstr = sys.argv[1][1:]
else:
rectright = marginright
fillrectwidth = rectleft
rectleft = 0
if len(sys.argv) > 2:
if sys.argv[2] == '[]':
sideflag = 1
elif sys.argv[2][0] == '(' and sys.argv[2][-1] == ')':
sidecolor = eval(sys.argv[2])
sideflag = 1
#------------------------------------------------------------
fontsize = 24
fontfile = r'd:\python\tools\font\arial.ttf'
tx = 0
ty = 0
if len(formularstr) > 0:
if formularstr.isnumeric():
formularstr = '(%s)'%formularstr
tx = rectright - rectleft - fontsize * len(formularstr) / 2
ty = (rectbottom - recttop - fontsize) / 2
#------------------------------------------------------------
SIDE_WIDTH = 10
if sideflag > 0:
# rectleft = rectleft - SIDE_WIDTH
recttop = recttop - SIDE_WIDTH
# rectright = rectright + SIDE_WIDTH
rectbottom = rectbottom + SIDE_WIDTH
ty = ty + SIDE_WIDTH
image = Image.open(mathtypepic).crop((rectleft, recttop, rectright+1, rectbottom+1))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(fontfile, size=fontsize)
if fillrectwidth > 0:
draw.rectangle((0, 0, fillrectwidth, rectbottom+1-recttop), fill=(255,255,255), outline=(255,255,255))
draw.text((tx, ty), formularstr, (0, 0, 0), font=font)
if sideflag > 0:
draw.rectangle((0, 0, rectright - rectleft, rectbottom - recttop), outline=sidecolor)
image.save(r'd:\temp\1.bmp')
output = BytesIO()
image.convert('RGB').save(output, 'BMP')
data = output.getvalue()[14:]
output.close()
send_to_clipboard(win32clipboard.CF_DIB, data)
#------------------------------------------------------------
printf("\a")
time.sleep(.1)
#------------------------------------------------------------
tspsendwindowkey(csdn_window, 'v', control=1)
for i in range(5):
time.sleep(.2)
readdata = tspread()
# printf(readdata)
if readdata[2] == 1: break
if readdata[7] != 0: break
if readdata[8] != 0: exit()
if readdata[9] != 0: exit()
tspsendwindowkey(csdn_window, 'a', control=1)
tspsendwindowkey(csdn_window, 'c', control=1)
if clipboard.paste().find('在这里插入图片描述') >= 0:
tspbeep(1500, 200)
time.sleep(.1)
break
printf('\a')
#------------------------------------------------------------
for i in range(20):
readdata = tspread()
if readdata[7] == 0 and readdata[8] == 0 and readdata[9] == 0: break
tspbeep(2500, 15)
time.sleep(.25)
#------------------------------------------------------------
#tspsendwindowkey(csdn_window, 'a', control=1)
#tspsendwindowkey(csdn_window, 'c', control=1)
#------------------------------------------------------------
pastestr = clipboard.paste().split('
if len(pastestr) < 2:
printf("Can not find the ![Insert picture] discriptor !\a")
exit()
for i in range(2):
tspsendwindowkey(csdn_window, '%c'%M1_END, vk=1)
tspsendwindowkey(csdn_window, 'v', control=1)
time.sleep(1)
printf('\a')
time.sleep(.5)
tspsendwindowkey(csdn_window, 'a', control=1)
tspsendwindowkey(csdn_window, 'c', control=1)
pastestr = clipboard.paste().split('
if len(pastestr) >= 2: break
if len(pastestr) < 2:
printf("Can not find the ![Insert picture] discriptor !\a")
exit()
#------------------------------------------------------------
tspsendwindowkey(csdn_window, 'z', control=1)
#------------------------------------------------------------
pastestr = pastestr[1].split(')')[0].split('?')[0]
#------------------------------------------------------------
widthstr = '=%dx'%int((rectright - rectleft) * 0.68)
morestring = ''
insertstring = ''
pic_pos_str = 'pic_center'
insertstring = '\r\n'%(insertstring, pastestr, pic_pos_str, widthstr)
#------------------------------------------------------------
clipboard.copy(insertstring)
tspsendwindowkey(csdn_window, 'v', control=1)
time.sleep(.2)
clipboard.copy('')
tspfocuswindow(csdn_window)
#------------------------------------------------------------
# END OF FILE : MTPIC2CSDN.PY
#============================================================
文章来源: zhuoqing.blog.csdn.net,作者:卓晴,版权归原作者所有,如需转载,请联系作者。
原文链接:zhuoqing.blog.csdn.net/article/details/107335408
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)