I have written a Python 2.6.6 script in order to make tables by taking the third column of every text file in a particular subgroup (signal and background in this case[particle physics]). However, I used the exec
command too often and I think this code can be written more elegantly.
#!/usr/bin/pythonimport sysstringpu = ["50PU", "140PU"]stringsig = ["NM1", "NM2", "NM3", "Scenario4", "Scenario6"]stringbkg = ["TTbar", "DiBoson", "TopJets", "BosonJets"]for a in range(len(stringsig)): exec("FILESIG"+str(a)+" = open('SummerStd_'+stringpu[1]+'_'+stringsig[a]+'.txt', 'r')") exec("LINESIG"+str(a)+" = FILESIG"+str(a)+".readlines()")for b in range(len(stringbkg)): exec("FILEBKG"+str(b)+" = open('SummerStd_'+stringpu[1]+'_'+stringbkg[b]+'.txt', 'r')") exec("LINEBKG"+str(b)+" = FILEBKG"+str(b)+".readlines()")table = open('table.txt', 'w')table.write("\\begin{table}[h] \n")table.write("\\centering \n")table.write("\\begin{tabular}{|c|c|c|c|c|c|} \n")table.write("\\hline & \\textbf{NM1} & \\textbf{NM2} & \\textbf{NM3} & \\textbf{STOC} & \\textbf{STC} \\\\ \n")n = 0for line in range(len(LINESIG0)): n += 1 for i in range(len(stringsig)): exec("wordsig"+str(i+1)+" = LINESIG"+str(i)+"[line].split()") if n > 2: table.write("\hline \n") table.write(wordsig2[2]+"& "+wordsig1[3]+"& "+wordsig2[3]+"& "+wordsig3[3]+"& "+wordsig4[3]+"& "+wordsig5[3]+" \\\\ \n")table.write("\hline \n")table.write("\end{tabular} \n")table.write("\end{table} \n")table.write("\\begin{table}[h] \n")table.write("\\centering \n")table.write("\\begin{tabular}{|c|c|c|c|c|c|} \n")table.write("\\hline & \\textbf{TTbar} & \\textbf{DiBoson} & \\textbf{TopJets} & \\textbf{BosonJets} \\\\ \n")n = 0for line in range(len(LINEBKG0)): n += 1 for i in range(len(stringbkg)): exec("wordbkg"+str(i+1)+" = LINEBKG"+str(i)+"[line].split()") if n > 2: table.write("\hline \n") table.write(wordbkg2[2]+"& "+wordbkg1[3]+"& "+wordbkg2[3]+"& "+wordbkg3[3]+"& "+wordbkg4[3]+" \\\\ \n")table.write("\hline \n")table.write("\end{tabular} \n")table.write("\end{table} \n")table.close()
I took courses on programming in Python before, but I do not remember the concepts of dictionaries and how to assign variables with dynamic names (such as changing inside a for
loop).