file_dir = r"C:\Users\weiye\Documents\wwy sync\23届\四月错题重做"
filelist = [] #列表为空默认处理所有讲义
output_gloss_filename= "错题重做参考答案"

import os,re,json


if len(filelist) == 0:
    filelist = [f for f in os.listdir(file_dir) if ".tex" in f]



with open("../题库0.3/Problems.json","r",encoding = "u8") as f:
    pro_dict = json.loads(f.read())

output_data = ""

for filename in filelist:
    outfilename = os.path.split(filename)[1][:-4]+"答案"
    with open(os.path.join(file_dir,filename),"r",encoding = "u8") as f:
        data = f.read()

    ids = re.findall(r"\((\d{6})\)",data)
    if len(ids) > 0:
        print("正在生成: ",outfilename)
        output_data += ("\n\n"+r"\section{"+outfilename.replace("_","-")+"}\n\n")
        output_data += ("\n\n"+r"\begin{enumerate}"+"\n\n")
        for id in ids:
            problemset = pro_dict[id]
            content = problemset["content"]
            solution = problemset["solution"]
            answer = "\\textcolor{red}{" + (problemset["ans"] if problemset["ans"] != "" else "\\textcolor{blue}{暂无答案}") + "}"
            output_data += "\\item " + "("+id+") " + content + "\n\n" + "答案: " + answer + "\n\n" 
        output_data += ("\n\n"+r"\end{enumerate}"+"\n\\newpage\n\n")

with open("模板文件/试卷答案模板.txt","r",encoding = "u8") as f:
    outlatex = f.read()

outlatex = outlatex.replace("内容待替换",output_data)
outlatex = outlatex.replace("标题文字待处理",output_gloss_filename.replace("_","-"))

outfile = os.path.join("临时文件",output_gloss_filename+".tex")
with open(outfile,"w",encoding="u8") as f:
    f.write(outlatex)

outfile = outfile.replace("\\","/")

print("编译 "+outfile+" 中")
os.system("xelatex -interaction=batchmode -output-directory=临时文件 " + outfile)
print(os.system("xelatex -interaction=batchmode -output-directory=临时文件 " + outfile))




    