栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

用Python批量替换LaTeX公式首尾标记

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用Python批量替换LaTeX公式首尾标记

我们知道对于识别 LaTeX 公式而言,$是行内公式首尾标记,$$是独立公式首尾标记

但笔者要想将 LaTeX 文章放在网页上,不同插件支持识别 LaTeX 的公式首尾标记不一样,比如有的以[和]为首尾标记,有的以[latex]和[/latex]为首尾标记

这就需要批量替换文本,在这里笔者用 Python 写了一个简单脚本进行替换

全局替换首尾标记

如果是想全局替换首尾标记,可以参考如下代码,含义为:

  • 将独立公式首尾标记替换成[latex display=true]和[/latex]
  • 将行内公式首尾标记替换成[latex]和[/latex]
content=open('input.md','r',encoding='utf-8')
with open('output.md',"w",encoding='utf-8') as f:
    isDisplayHead = True #是否为独立公式首标记
    isInlineHead = True #是否为行内公式首标记
    for line in content:
        for i in range(0,line.count('$$')):
            if(isDisplayHead):
                line=line.replace('$$','[latex display=true]',1)
            else:
                line=line.replace('$$','[/latex]',1)
            isDisplayHead=not isDisplayHead
            
        for i in range(0,line.count('$')):
            if(isInlineHead):
                line=line.replace('$','[latex]',1)
            else:
                line=line.replace('$','[/latex]',1)
            isInlineHead=not isInlineHead

        f.write(line)
                
    f.flush() # 写入硬盘            
    f.close() #关闭文件,并刷新
根据特定内容替换首尾标记

如果是想根据搜索到特定内容才替换首尾标记,可以参考如下代码,含义为:

  • 将含有begin的公式块首尾标记替换成[latex display=true]和[/latex]
  • 将含有lim或|_的公式块首尾标记替换成[latex]和[/latex]
  • 未出现上述字符串的公式块首尾标记保持不变
content=open('input.md','r',encoding='utf-8')
with open('output.md',"w",encoding='utf-8') as f:
    isDisplayHead = True
    isInlineHead = True
    cnt = 0
    for line in content:
        begin = 0
        for i in range(0,int(line.count('$')/2)):
            
            left = line.find('$',begin)
            right = line.find('$', left+1)
            begin = right+1
            
            res = 0
            #res表搜索结果,0代表没有出现对应字符串,1表示行内公式,2表示独立公式

            if not(line.find('\begin',left,right+1)==-1):
                res = 2
                lsign = "[latex display=true]"
                rsign = "[/latex]"
                
            #极限和求导(y|x=x0表示法)
            elif not(line.find('\lim',left,right+1)==-1
                     and line.find('|_',left,right+1)==-1):
                res = 1
                lsign = "[latex]"
                rsign = "[/latex]"
            else:
                res = 0
                continue
            
            if(left!=0): head = line[:left]
            else: head = ''
        
            if(right!=len(line)-1): rear = line[right+1:]
            else: rear = '';
            
            line =  head + lsign +  line[left+1:right] + rsign + rear
                
        f.write(line)
                
    f.flush() # 写入硬盘            
    f.close() #关闭文件,并刷新
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/948447.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号