【发布时间】:2021-08-01 10:07:08
【问题描述】:
我编写了一个代码来清理LaTex(只是一个字符串),我想在其中插入空格以标记字符串。我的代码如下:
def insert_spaces(sentence):
'''
Add a space around special characters, number and digits. So "2x+y -1/3x" becomes: "2 x + y - 1 / 3 x"
'''
dummy_list = []
splitted_sent = list(sentence)
for i in range(len(splitted_sent)-1):
dummy_list.append(splitted_sent[i])
if splitted_sent[i].isalpha(): # if it is an alphabet
if splitted_sent[i+1].isdigit() or (not splitted_sent[i+1].isalnum()):
dummy_list.append(' ')
elif splitted_sent[i].isdigit(): # if it is a number
if splitted_sent[i+1].isalpha() or (not splitted_sent[i+1].isalnum()):
dummy_list.append(' ')
elif (not splitted_sent[i].isalnum()) and (splitted_sent[i] not in [' ','\\']): # if it is a special char but not ' ' already
if splitted_sent[i+1].isalnum():
dummy_list.append(' ')
dummy_list.append(splitted_sent[-1])
return ''.join(dummy_list)
例如,如果我的原始查询是:
'ds^{2} = (1 - {qcos\\theta\\over r})^{2\\over 1 + \\alpha^{2}}\\lbrace dr^2+r^2d\\theta^2+r^2sin^2\\theta d\\varphi^2\\rbrace -{dt^2\\over (1 - {qcos\\theta\\over r})^{2\\over 1 + \\alpha^{2}}}\\, .\\label{eq:sps1} \\widetilde\\gamma_{\\rm hopf}\\simeq\\sum_{n>0}\\widetilde{G}_n{(-a)^n\\over2^{2n-1}}\\label{H4}3455'
然后我希望它被清理为:
'd s ^ { 2 } = ( 1 - { q c o s \\theta \\over r } ) ^ { 2 \\over 1 + \\alpha ^ { 2 } } \\lbrace d r ^ 2 + r ^ 2 d \\theta ^ 2 + r ^ 2 sin ^ 2 \\theta d \\varphi ^ 2 \\rbrace -{ d t ^ 2 \\over ( 1 - { q c o s \\theta \\over r } ) ^ { 2 \\over 1 + \\alpha ^ { 2 } } } \\ , . \\label { eq : sps 1 } \\widetilde \\gamma _ { \\rm h o p f } \\simeq \\sum _ { n > 0 } \\widetilde { G } _ n { ( - a ) ^ n \\over 2 ^ { 2 n - 1 } } \\label { H 4 } 3 4 5 5'
The above result is a product of this this script 基本上调用this KaTex script
但是现在,我得到的结果是:
'ds ^{ 2 } = ( 1 - { qcos \\theta \\over r })^{ 2 \\over 1 + \\alpha ^{ 2 }}\\lbrace dr ^ 2 + r ^ 2 d \\theta ^ 2 + r ^ 2 sin ^ 2 \\theta d \\varphi ^ 2 \\rbrace -{ dt ^ 2 \\over ( 1 - { qcos \\theta \\over r })^{ 2 \\over 1 + \\alpha ^{ 2 }}}\\, .\\label { eq : sps 1 } \\widetilde \\gamma _{\\rm hopf }\\simeq \\sum _{ n > 0 }\\widetilde { G }_ n {(- a )^ n \\over 2 ^{ 2 n - 1 }}\\label { H 4 } 3455'
有没有什么方法可以在 RegEx 的帮助下达到同样的效果?
【问题讨论】:
-
您想要的输出似乎也将
\\over转换为frac?您能否提供有关您尝试应用的转换的更多信息? -
这是我从 repo 本身使用的唯一代码。现在,我将只更新所需的输出。