首页 > 其他分享 >替换掉tex文件的关键字以便于翻译

替换掉tex文件的关键字以便于翻译

时间:2023-05-27 15:45:56浏览次数:37  
标签:replaceNum replaceChar pattern textContent tex 关键字 re 替换

遇到的问题:找到了一篇文献的Tex文件,尝试使用翻译软件翻译成中文以便于阅读,但机翻会极其智障地把不该翻译的也给翻译了,比如

\begin{document}

给翻译成了

\开始{文档}

因此,尝试使用正则表达式将Tex中没有必要翻译的关键字与公式给替换掉

(1)将关键字替换掉

#将Tex文件的关键字及公式替换掉并保存下来,防止被翻译软件翻译掉
import os
import re
replaceDict=[
    r'(\$\$[^\$]+\$\$)', #一对$$符号中间夹着的数学表达式
    r'(\$[^\$]+\$)', #一对$符号中间夹着的数学表达式
    r'(\\[a-zA-Z]+{[^{}]+})', #\xxx{xxx}形式的命令
    r'(\\[a-zA-Z]+)' #\xxx形式的命令
]
expressDict=[
    r'(\\begin{equation}|\\end{equation})',
    r'(\\begin{equation\*}|\\end{equation\*})',
    r'(\\begin{align}|\\end{align})',
    r'(\\begin{align\*}|\\end{align\*})',
    r'(\\begin{table}|\\end{table})',
    r'(\\begin{table\*}|\\end{table\*})',
    r'(\\\[|\\])',
    r'([|])',
    r'({|})',
]
# 注意,如果不在字符串前面使用r符号,则反斜杠会被Python解释器转义一次,再被正则表达式转义一次
# 注意,右中括号不需要转义
# 注意,当大括号内容不含数字时大括号不需要转义
# 吐槽,正则表达式的可读性和可维护性为0
replaceChar='の'#用于标记被替换掉的关键字的字符,最好是原文里没有且不会被翻译软件读取并改变的
splitChar='ん'#用于在存储关键字临时文件中分隔
inputFileName='main.tex'
outputFileName='out.tex'
tempFileName='temp.txt'
textContent=open(inputFileName,'r',encoding='utf-8').read()

replacedContent=[]

# 替换关键字部分
with open(tempFileName,'w',encoding='utf-8') as ftempout:
    replaceNum=0
    # 替换掉导言区
    pattern=re.compile(r'(\\begin{document})')
    s=pattern.split(textContent)
    ftempout.write(s[0]+s[1]+splitChar)
    s[0]=replaceChar+str(replaceNum)+replaceChar
    s[1]=''
    replaceNum=replaceNum+1
    textContent=''.join(s)

    # 替换掉数学表达式
    for w in expressDict:
        pattern=re.compile(w)
        s=pattern.split(textContent)
        # for j in range(len(s)):
        #     ftempout.write("\n%%%%\n"+s[j]+"\n%%%%\n")
        # exit()
        j=0
        while j < len(s):
            if pattern.match(s[j]) != None:
                print(s[j]+s[j+1]+s[j+2])
                ftempout.write(s[j]+s[j+1]+s[j+2]+splitChar)
                replacedContent.append(s[j]+s[j+1]+s[j+2])
                s[j]=replaceChar
                s[j+1]=str(replaceNum)
                s[j+2]=replaceChar
                replaceNum=replaceNum+1
                j=j+2
            j=j+1
        textContent=''.join(s)
        # 注意,Python中的for in range()循环的循环变量无法像C++那样在循环中改变

    for w in replaceDict:
        pattern=re.compile(w)
        s=pattern.split(textContent)
        for j in range(len(s)):
            if pattern.match(s[j]) != None:
                print(s[j])
                ftempout.write(s[j]+splitChar)
                s[j]=replaceChar+str(replaceNum)+replaceChar
                replaceNum=replaceNum+1
        textContent=''.join(s)
with open(outputFileName,'w',encoding='utf-8') as fout:
    fout.write(textContent)

(2)替换回来

#将Tex文件的关键字及公式替换掉并保存下来,防止被翻译软件翻译掉
import os
import re
replaceChar='の'#用于标记被替换掉的关键字的字符,最好是原文里没有且不会被翻译软件读取并改变的
splitChar='ん'#用于在存储关键字临时文件中分隔
inputFileName='main.tex'
outputFileName='out.tex'
translatedFileName='transed.tex'
tempFileName='temp.txt'
finalOutputFileName='out2.tex'
replacedContent=re.split(splitChar,open(tempFileName,'r',encoding='utf-8').read())
# print(replacedContent)
textContent=open(translatedFileName,'r',encoding='utf-8').read()
contentPattern='('+replaceChar+r'[0-9]+'+replaceChar+')'
pattern=pattern=re.compile(contentPattern)
while re.search(replaceChar,textContent)!= None:
    s=re.split(contentPattern,textContent)
    for j in range(len(s)):
        if pattern.match(s[j])!= None:
            # print(int(s[j][1:-1]),replacedContent[int(s[j][1:-1])])
            s[j]=replacedContent[int(s[j][1:-1])]
    textContent=' '.join(s) #不加空格的话关键字和文本可能会粘连在一起造成编译错误
with open(finalOutputFileName,'w',encoding='utf-8') as fout:
    fout.write(textContent)

 

标签:replaceNum,replaceChar,pattern,textContent,tex,关键字,re,替换
From: https://www.cnblogs.com/isakovsky/p/17436830.html

相关文章

  • [ICDE 2023] Minimizing the Influence of Misinformation via Vertex Blocking
    MinimizingtheInfluenceofMisinformationviaVertexBlockingMotivationandApplication其实就是经典的RumorBlocking问题,即通过一系列的操作使得rumor在社交网络中的影响力最小。主流的方法有三种:找到一组seedset去和rumor节点竞争,社交网络中的节点都只能被激活一次,......
  • 位置参数和关键字参数
    位置参数:括号中依次填入的变量名位置参数:括号中依次填入的变量名位置形参:在定义阶段,括号中从左到右依次填入的变量名位置形参:在定义阶段,括号中从左往右依次填入的变量名位置实参:在调用阶段,括号中从左往右依次传入的数据值位置实参:在调用阶段,括号中从左到右依次依次转......
  • ARM Cortex-A72 CPU All In One
    ARMCortex-A72CPUAllInOneRaspberryPi4B,BCM27114核心1.5GHz64位CPU/RaspberryPi4B,BCM27114核心1.8GHz64位CPUCortex-A72https://developer.arm.com/Processors/Cortex-A72https://developer.arm.com/documentation/100095/0003/Introduction/A......
  • 自定义占位符替换工具类
    添加依赖<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version></dependency>工具类importorg.apache.commons.lang3.StringUtils;importo......
  • Codeforces 1444E - Finding the Vertex
    非常神秘的一道题,当之无愧的*3500。首先考虑转化题意。考虑一种决策树,由于我们每次问一条边之后,相当于会根据信息删掉两个连通块中的一个,因此一种决策树实际上对应了原树的一棵边分树。而为了让最坏情况下的询问次数最少,我们目标实际上是最小化边分树的深度。考虑借鉴P5912JA......
  • 英文双引号替换成中文双引号
    1.字符串中的英文双引号变成中文双引号///<summary>///替换字符串中的英文双引号为中文双引号///</summary>///<paramname="str"></param>///<returns></returns>publicstaticstringReplaceYinHaoEnToCn(stringstr){stringnewStr="......
  • 异步编程(Thread、ThreadPool、Task、异步关键字async/await)
    一、什么是异步Thread,是微软.Net1.0推出;ThreadPool 是微软.Net2.0推出;Task是微软.Net4.0推出;async/await是微软.Net5.0推出;       同步和异步主要用于修饰方法。当一个方法被调用时,调用者需要等待该方法执行完毕并返回才能继续执行,我们称这个方法是同步方法;当一个方......
  • 合集 替换子关键词
    代码list_ZFI077=df_1.columns.tolist()df_ZFI077=df_1.columns.to_frame(name="列名")#先不重置索引drop依据索引df_ZFI077_1=df_ZFI077.copy().reset_index(drop=True)#index.to_frame()后需重置索引方便赋值fori,jinenumerate(list_ZFI077):ifdf_ZFI0......
  • Latex 标题与正文重合问题
    在使用Latex的时候出现以下问题:即文章标题与文章正文出现重叠,\section{}失去了添加空白的功能,目前没有找到合适的解决方案,只能通过手动增加空白来解决:点击查看代码\vskip0.5in\section{这是一个章节名}效果如下:初步推断是宏包与文档格式冲突,还没有找出原因。这是一......
  • golang·context
    Context引入Q:如何优雅地控制子协程(goroutine)退出?利用waitgroup+全局变量notify退出packagemainimport( "fmt" "sync" "time")//引入:为什么需要context?varwgsync.WaitGroupvarnotifybool//默认值为falsefuncf(){ deferwg.Done() for{ fm......