Quizbank/Python/LaTex
Jump to navigation
Jump to search
This Python code converts a quiz that looks like this wiki page into one that can be viewed in either this LaTex format or as this pdf file.
##This code reads only the question of a numerical quiz's sample.
# This version only prints hello world (after createing ...prelude...)
#I have a problem with the answers: placing the begin and end to choices
import os, csv, re, time, shutil, random, sys, pickle
alphabet = "abcdefghijklmnopqrstuvwxyz"
quizNamePy=os.path.basename(__file__)[:-3]
newPermaLink = ""
quizNameLatex=quizNamePy.replace('_',r'''\_''')
#print('quizNameLatex=',quizNameLatex)
screenPrint=False # a more flexible debug system.
codeTest=False # includes a section for code testing
nokeyTest=False #default is false
class Quiz: #The quiz is strictly a wikitext entity
def __init__(self):
self.name =""
self.permaLink = ""
self.wiki = ""
self.quizType = ""
self.attribution = ""
self.user = ""
self.numberOfQuestions = 0
self.questions = []
self.answers = []
self.correctAnswers = []
quiz=Quiz()
#######################################################################
####################### Py2Latex UPGRADES FROM WIKITEXT TO LATEX ######
######################################################################3333
def Py2Latex(string):
#string=string.replace('_',r'''\_''') I do this inside the loops
string=string.replace('½MR<sup>2</sup>',
r''' \(\tfrac{1}{2}MR^2\)''')
#permanent collection
string=string.replace('<sup>',r'''\textsuperscript{''')
string=string.replace('</sup>',r'''}''')
string=string.replace('<sub>',r'''\textsubscript{''')
string=string.replace('</sub>',r'''}''')
string=string.replace('θ',r'''\straighttheta\ ''')
string=string.replace('ω',r'''\greekomega\ ''')
string=string.replace(r'''<math>''', '\\(')
string=string.replace(r'''</math>''', '\\)')
string=string.replace('<br>','')
string=string.replace('<br/>','')
#subject to change
string=string.replace(r'''m^3''',r'''m\textsuperscript{3}''')
######################################################################
################################################ Substiture Image here
#################################################################3
image1='[[File:Yo yo moment of inertia.jpg|right|280px]]'
new1=r'''Yo_yo_moment_of_inertia.png'''
replace1=wrapImage1(new1)
string=string.replace(image1,replace1)
## image2='[[File:Three forces on fulcrum.jpg|right|240px]]'
## new2='Three_forces_on_fulcrum.png'
## replace2=wrapImage2(new2)
## string=string.replace(image2,replace2)
# end Py2Latex:
return(string)
#################################### IMAGES GO HERE ################
def wrapImage1(newname): #This akwardly places image in text. But it's robust.
########################################################### ADJUST WIDTHS
################################################## and include in preamble below
image1=r'''
\includegraphics[width=0.2\textwidth]{'''
image1+=newname+'}'
return image1
##def wrapImage2(newname):
## image2=r'''
## \includegraphics[width=0.240\textwidth]{'''
## image2+=newname+'}'
## return image2
###Open read-only copy of wikiquiz
quizFile=open('./wbank/'+quizNamePy+'.txt','r')
line=quizFile.readline()
while line[:16] != "==*_Quizbank_*==" and line[:18] != "===*_Quizinfo_*===":
line = quizFile.readline()
if line == "":
x=input("unable to read Hit the end?")
#here we get the tags:
while line[:14] != "===*_Quiz_*===":
#print(line)
tag = re.search('\*_[a-zA-Z]+_\*',line)#python needs \ before *
if tag !=None: #i.e. if we see this tag we remove unwanted stuff:
tag = tag.group(0)
line = line.replace(tag,"")
line = line.strip("\n")
line = line.strip(" ")#all unwanted stuff is removed
if tag == "*_Name_*": #Now go through all possible tags
quiz.name = line
elif tag == "*_Permalink_*":
startnum=line.find('Permalink/')+10
endnum=len(line)-2
print('\noldid is ',line[startnum:endnum],'\n')
quiz.permaLink = line[startnum:endnum]
elif tag == "*_wiki_*":
quiz.wiki = line
elif tag == "*_numerical_*":
quiz.quizType = "numerical"
if screenPrint==True:
print(quiz.quizType)
elif tag == "*_conceptual_*":
quiz.quizType = "conceptual"
elif tag == "*_Attribution_*":
quiz.attribution = line
if screenPrint==True:
print('original quiz attribution) ', quiz.attribution)
elif tag == "*_See_*":
quiz.user = line
line = quizFile.readline() #Now the tags are done, we readif
if screenPrint==True:
print(line, '(has just been read). Now we know:')
print('name=',quiz.name)
print('permaLink=',quiz.permaLink)
print('wiki=',quiz.wiki)
print('quizType=',quiz.quizType)
print('user=',quiz.user)
print('numberOfQuestions=',quiz.numberOfQuestions)
print('next we begin the Latex markup\n')
#globalFootnote is attibution for all questions. See also localFootnoote
globalFootnote=' placed in Public Domain by Guy Vandegrift: '
globalFootnote+= r'''{\url{https://en.wikiversity.org/wiki/special:permalink/'''
globalFootnote+= quiz.permaLink+'}'
#The LaTex markup begins with wikitext header. Latex comment (%) begins each line:
longstring =""
longstring+='% See [[special:permalink/'+quiz.permaLink+']]'
longstring+=' for a wikitext version of this quiz.[[Category:QB/LaTeXpdf]]\n'
longstring+='%===LaTexMarkup begin===\n'
longstring+='%[[File:Quizbankqb_{{SUBPAGENAME}}.pdf|thumb|See'
longstring+='[[:File:Quizbankqb_{{SUBPAGENAME}}.pdf]]]]\n'
longstring+='%CurrentID: {{REVISIONID}}\n'
longstring+='%PDF: [[:File:Quizbankqb_{{SUBPAGENAME}}.pdf]]'
longstring+='%Required images: [[file:Wikiversity-logo-en.svg|45px]]'
#add more images here: ###################### add images here ### ADD IMAGES
############################################# Paste Commons image address
#longstring+='[[File:Hinge on wall statics.jpg|45px]]'
##longstring+='[[File:Yo yo moment of inertia.jpg|45px]]'
###########################################################################
########################################################### ADJUST HERE
longstring+=r'''
%<syntaxhighlight "lang=latex">
%This code creates both the question and answer key using \newcommand\mytest
%%% EDIT QUIZ INFO HERE %%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand{\quizname}{'''+Py2Latex(quiz.name)+'}\n\n'
longstring+=r'''\newcommand{\quiztype}{'''
longstring+=quiz.quizType+r'''}%[[Category:QB/'''
longstring+=quiz.quizType+']]\n'
#################################### BEGIN PREAMBLE #####
longstring+=r'''%%%%% PREAMBLE%%%%%%%%%%%%
\newif\ifkey %estabkishes Boolean ifkey to turn on and off endnotes
\documentclass[11pt]{exam}
\RequirePackage{amssymb, amsfonts, amsmath, latexsym, verbatim,
xspace, setspace,datetime}
\RequirePackage{tikz, pgflibraryplotmarks, hyperref}
\usepackage[left=.5in, right=.5in, bottom=.5in, top=.75in]{geometry}
\usepackage{endnotes, multicol,textgreek} %
\usepackage{graphicx} %
\singlespacing %OR \onehalfspacing OR \doublespacing
\parindent 0ex % Turns off paragraph indentation
\hypersetup{ colorlinks=true, urlcolor=blue}
% BEGIN DOCUMENT
\begin{document}'''
longstring+='\n\\title{'+quizNameLatex+'}'
#print('diagnostic:','\n\\title{\\'+quizNameLatex+'}')
longstring+=r'''
\author{The LaTex code that creates this quiz is released to the Public Domain\\
Attribution for each question is documented in the Appendix}
\maketitle'''
# before Toc begin
longstring+=r'''
\begin{center}
\includegraphics[width=0.15\textwidth]{666px-Wikiversity-logo-en.png}
\\Latex markup at\\
\footnotesize{ \url{https://en.wikiversity.org/wiki/special:permalink/'''
longstring+=quiz.permaLink+r'''}}
\end{center}'''
#before toc end
longstring+=r'''
\begin{frame}{}
\begin{multicols}{3}
\tableofcontents
\end{multicols}
\end{frame}
'''
####################### BEGAN DOCUMENT ABOVE#####
if codeTest:###### \section{codeTest} ####
longstring+=r'''\section{codeTest}
This document was created on: \today\ at \currenttime.\\
10<sup>3</sup>
'''
longstring+='\n Test this linke \n'+globalFootnote+'\n\n'
######################################### \section{Quiz}
longstring+=r'''\pagebreak\section{Quiz}
\keytrue
\printanswers
\begin{questions}'''
if nokeyTest==True:
longstring+=r'''\keyfalse'''+'\n'
################################ CONCEPTUAL QUIZ ##############
if quiz.quizType == "conceptual":
longstring+='\\keytrue\n'
endOfQuiz=r'''</quiz'''
inQuestion=False
while line[:len(endOfQuiz)]!=endOfQuiz and line!='':
if screenPrint:
print(line)
################################## I WILL PASTE HERE
tag = re.search('{(<!--.*-->.*)}\s*?\n',line)#seeks question-comment
#re=regular expression, /search is a regular expression object
#that seeks the pattern \s matches Unicode whitespace characters;
#*? makes match non-greedy
if tag != None: #i.e., if we found a question
inQuestion=True
st=tag.groups(0)[0]
#print('st=tag.groups(0)[0]=',st) #remove
startHidden=st.find('<!-')
stopHidden=st.find('-->')
HiddenInfo=st[startHidden+4:stopHidden]
HiddenInfo=HiddenInfo.replace(r'''_''',r'''\_''')
FootNote='\\ifkey\\endnote{'+HiddenInfo
FootNote+=globalFootnote+'}'
QuestionOnly=st[stopHidden+3:]
# Make question
st='\n\\question '+QuestionOnly + FootNote +'}\\fi'
longstring+=st+'\n\\begin{choices}\n'
if line[0]=='-':
longstring+='\\choice '+line[1:].lstrip()
## if screenPrint==True:
## print("-: "+line[1:])
if line[0]=='+':
longstring+='\\CorrectChoice '+line[1:].lstrip()
## if screenPrint==True:
## print("+: "+line[1:])
if line[0] not in ['+','-','{'] and inQuestion==True:
longstring+='\\end{choices}\n'
inQuestion=False
line = quizFile.readline()
#Ends while line[:16] != "====*_Question_*" and \
longstring+='\n'
longstring+='\\end{questions}\n\\newpage'
#################################### i JUST PASTED ABOVE
#inQuestion==False# This supresses the endquiz
########################### NUMERICAL QUIZ #####################
elif quiz.quizType == "numerical": # scanning numerical quizzes
inQuestion=False
while line[:16] != "====*_Question_*" and \
line!="": #this terminates at first question in renditions
tag = re.search('{(<!--.*-->.*)}\s*?\n',line)#seeks question-comment
#re=regular expression, /search is a regular expression object
#that seeks the pattern \s matches Unicode whitespace characters;
#*? makes match non-greedy
if tag != None: #i.e., if we found a question
inQuestion=True
st=tag.groups(0)[0]
#print('st=tag.groups(0)[0]=',st) #remove
startHidden=st.find('<!-')
stopHidden=st.find('-->')
HiddenInfo=st[startHidden+4:stopHidden]
HiddenInfo=HiddenInfo.replace(r'''_''',r'''\_''')
FootNote='\\ifkey\\endnote{'+HiddenInfo
FootNote+=globalFootnote+'}'
QuestionOnly=st[stopHidden+3:]
# Make question
st='\n\\question '+QuestionOnly + FootNote +'}\\fi'
longstring+=st+'\n\\begin{choices}\n'
if line[0]=='-':
longstring+='\\choice '+line[3:].lstrip()
## if screenPrint==True:
## print("-: "+line[1:])
if line[0]=='+':
longstring+='\\CorrectChoice '+line[3:].lstrip()
## if screenPrint==True:
## print("+: "+line[1:])
if line[0] not in ['+','-','{'] and inQuestion==True:
longstring+='\\end{choices}\n'
inQuestion=False
line = quizFile.readline()
#Ends while line[:16] != "====*_Question_*" and \
longstring+='\n'
longstring+='\\end{questions}\n\\newpage'
################### Begin renditions===
longstring+='\\section{Renditions}\n'
nQuestion=0
inRendition=False #need this to suppres \end{choices} at start
firstRendition=True
while line!= "":
line.replace('\n', ' ').replace('\r', '')
if line[:14]=='====*_Question':
if not firstRendition:
longstring+='\\pagebreak\n'
longstring+="\\end{choices}\n"
firstRendition=False
nQuestion+=1
if inRendition: #do not print this if it's the first:
longstring+='\n\\end{questions}%%%%%%%% end questions\n'
inRendition = True #henceforth print abobe
longstring+='\\subsection{}%%%% subsection '+str(nQuestion)
longstring+='\n\\begin{questions} %%%%%%% begin questions\n'
inQuestion=False #pause here
if line[:4]=='<!--':
inQuestion=True
stopHidden=line.find('-->')
HiddenInfo='footnote: '+line[4:stopHidden]
#HiddenInfo =
longstring+="\\question "+line[stopHidden+3:]#+HiddenInfo
longstring+='\n\\begin{choices} %%%%%%% begin choices\n'
if line[0]=='-':
longstring+=" \\choice " +line[3:]
if line[0]=='+':
longstring+=" \\CorrectChoice"+line[3:]
if line[0] not in ['+','-','<'] and inQuestion==True:
inQuestion=False
longstring+='\\end{choices} %%% end choices\n'
#ALWAYS THE LAST IN THIS WHILE LINE!-''
line = quizFile.readline()
longstring+='\\end{questions}\\pagebreak\n'
########################### Write endnotes and end document
if nokeyTest==True:
longstring+='\\endnote{testing purposes only}\n'
longstring+=r'''
\section{Attribution}
\theendnotes
\end{document}
<!This is a wiktext statment that does no harm to the LaTex markup (after end of document)-->
END LaTexMarkup
################################Invoke Py2Latex and write###
longstring=Py2Latex(longstring)
screenPrint=False
if screenPrint==True:
print('Final longstring\n',longstring)
screenPrint=False
with open('Quizbankqb_'+quizNamePy+'.tex','w') as outfile:
outfile.write(longstring)
print("This was a ",quiz.quizType, " quiz")
#########################################End of Python code