Extract (multiple) TeX environement to csv with python script

Viewed 128

My first question in python, pls be kind :)

Question

How do I handle the extraction of the .tex file (as described below) to a flat csv (with format below) ?

Context

I created all my MCQ in LaTeX. However exams are now 100% online... (sigh)

My LaTeX file has the basic following format

\documentclass[12pt]{exam}
​
\begin{document}

\begin{questions}
 \question What is the answer ? 
 \begin{oneparchoices}
 \choice 75
 \choice 80
 \CorrectChoice 85
 \choice None of the above
 \end{oneparchoices}
\end{questions}
\end{document}

I need now to provide a csv where the questions of the MCQ above would be displayed like (Incorrect,Correct, just to be clear

question,answer1,Cor/Inc,answer2,Cor/Inc,answer3,Cor/Inc ,answer4,Cor/Inc,answer5,Cor/Inc

And it would render like

What is the answer ?,Inc,70,Inc,75,Inc,80,Inc,85,Cor,None of the above,Inc

Each line would obviously be a new question.

What could correspond so far

I see the principle for environment between \begin and \end thanks to Extract figures from latex file

infile = open('MCQ.tex', 'r')
outfile = open('FlattenMCQ.csv', 'w')
extract_block = False
for line in infile:
    if 'begin{questions}' in line:
        extract_block = True
    if extract_block:
        outfile.write(line)
    if 'end{questions}' in line:
        extract_block = False
        outfile.write("------------------------------------------\n\n")

infile.close()
outfile.close()

Where I am stuck The recurisivity to test first \begin{questions} then \question then \begin{oneparchoices} then \choice or \CorrectChoice

0 Answers
Related