读出文件并将某行转换成正确的形式

Read out file and convert certain line into a correct form

我有问题。我正在读一个文件。 此文件包含缩写。但是,我只想阅读缩写。这也有效。但是,不是预期的格式,我想每行干净地保存缩写(请参见下面的所需输出)。问题是我得到了 '\t\acro{... 之类的东西。我怎样才能将其转换为我想要的输出?

def getPrice(symbol,
            shortForm,
            longForm):

    abbreviations = []
    with open("./file.tex", encoding="utf-8") as f:
         file = list(f)
    save = False
    for line in file:
        print("\n"+ line)
        if(line.startswith(r'\end{acronym}')):
            save = False
        if(save):
            abbreviations.append(line)
        if(line.startswith(r'\begin{acronym}')):
            save = True
        
    print(abbreviations)

if __name__== "__main__":
    getPrice(str(sys.argv[1]),
    str(sys.argv[2]),
    str(sys.argv[3]))


[OUT]
['\t\acro{knmi}[KNMI]{Koninklijk Nederlands Meteorologisch Instituut}\n', '\t\acro{test}[TESTERER]{T E SDH SADHU AHENSAD }\n']
\chapter*{Short}
\addcontentsline{toc}{chapter}{Short}
\markboth{Short}{Short}
\begin{acronym}[TESTERER]
    \acro{knmi}[KNMI]{Koninklijk Nederlands Meteorologisch Instituut}
    \acro{example}[e.g.]{For example}
\end{acronym}

期望的输出

{
  "abbreviation1": {
      "symbol": "knmi",
      "shortForm": "KNMI",
      "longForm": "Koninklijk Nederlands Meteorologisch Instituut",
   }
  "abbreviation2": {
      "symbol": "example",
      "shortForm": "e.g.",
      "longForm": "For example",
   }
}

您可以使用 re.findall() 捕获所有缩写,然后使用 json 模块将其转储到文件中。您的方法可能有效,但您必须进行大量手动字符串解析,这将是一个非常令人头疼的问题。 (请注意,可以解析任意 LaTeX 的程序需要比正则表达式更强大的东西;但是,由于我们解析的是 LaTeX 的一个非常小的子集,因此正则表达式在这里就可以了。)

import re
import json

data = r"""\chapter*{Short}
\addcontentsline{toc}{chapter}{Short}
\markboth{Short}{Short}
\begin{acronym}[TESTERER]
    \acro{knmi}[KNMI]{Koninklijk Nederlands Meteorologisch Instituut}
    \acro{example}[e.g.]{For example}
\end{acronym}"""

pattern = re.compile(r"\acro\{(.+)\}\[(.+)\]\{(.+)\}")
regex_result = re.findall(pattern, data)
final_output = {}
for index, (symbol, shortform, longform) in enumerate(regex_result, start=1):
    final_output[f'abbreviation{index}'] = \
        dict(symbol=symbol, shortform=shortform, longform=longform)

with open('output.json', 'w') as output_file:
    json.dump(final_output, output_file, indent=4)

output.json 包含以下内容:

{
    "abbreviation1": {
        "symbol": "knmi",
        "shortform": "KNMI",
        "longform": "Koninklijk Nederlands Meteorologisch Instituut"
    },
    "abbreviation2": {
        "symbol": "example",
        "shortform": "e.g.",
        "longform": "For example"
    }
}