Processing math: 100%

Créer un fichier LaTeX avec Python. Dans un article précédent, je vous expliquais comment, dans un fichier LATEX, on pouvait se servir de Python grâce à l’extension Pythontex.

Maintenant, je vais vous expliquer comment faire l’inverse, à savoir comment créer et compiler un fichier LATEX avec un programme Python.

L’objectif va être le même que dans l’article précédent (cas d’école) : créer 20 développements (avec double distributivité) aléatoires.

Créer un fichier LaTeX avec Python
Créer un fichier TeX et le compiler sous Python

Créer un fichier LaTeX avec Python: importation des modules nécessaires

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import os.path
import random
from sympy import Symbol
from sympy import expand
x=Symbol('x')
import os.path import random from sympy import Symbol from sympy import expand x=Symbol('x')
import os.path
import random
from sympy import Symbol
from sympy import expand
x=Symbol('x')

J’importe le module os car il va me servir à exécuter des commandes en lignes.

Ensuite, j’importe le module random car il est nécessaire dans notre contexte (dès lors qu’il y a choix aléatoire…).

J’utilise ensuite sympy pour les manipulations algébriques (c’est spécifique ici à ce que je souhaite faire). Je définis alors « x » comme le symbole désignant l’inconnue.

Créer un fichier LaTeX avec Python: construction du fichier

Le contenu du fichier va être défini par une succession de texte.

Créer un fichier LaTeX avec Python: définir le préambule

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def preambule(*packages):
p = ""
for i in packages:
p = p+"\\usepackage{"+i+"}\n"
return p
def preambule(*packages): p = "" for i in packages: p = p+"\\usepackage{"+i+"}\n" return p
def preambule(*packages):
	p = ""
	for i in packages:
		p = p+"\\usepackage{"+i+"}\n"
	return p

Cette fonction a pour but d’appeler tous les packages nécessaires.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
start = "\\documentclass[12pt,a4paper,french]{article}\n\\usepackage[utf8]{inputenc}\n"
start = start+preambule('amsmath','lmodern','babel')
start = start+"\\begin{document}\n\\begin{align*}\n"
end = "\\end{align*}\n\\end{document}"
start = "\\documentclass[12pt,a4paper,french]{article}\n\\usepackage[utf8]{inputenc}\n" start = start+preambule('amsmath','lmodern','babel') start = start+"\\begin{document}\n\\begin{align*}\n" end = "\\end{align*}\n\\end{document}"
start = "\\documentclass[12pt,a4paper,french]{article}\n\\usepackage[utf8]{inputenc}\n"
start = start+preambule('amsmath','lmodern','babel')
start = start+"\\begin{document}\n\\begin{align*}\n"

end = "\\end{align*}\n\\end{document}"

On commence par définir la classe utilisée (avec les options souhaitées) ainsi que l’encodage. Puis, on appelle tous les packages souhaités. Enfin, on commence le document.

Génération des égalités

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
body = ""
for n in range(21):
a = random.choice([1, -1]) * random.randint(2, 9)
b = random.choice([1, -1]) * random.randint(2, 9)
c = random.choice([1, -1]) * random.randint(2, 9)
d = random.choice([1, -1]) * random.randint(2, 9)
e = (a*x+b)*(c*x+d)
eresultchain = str(expand(e)) # on convertit le résultat en chaîne de caractères
eresultchain = eresultchain.replace('**','^') # on met au format TeX les exposants
eresultchain = eresultchain.replace('*','') # on élimine les symboles '*'
echain = str(e)
echain = echain.replace('*','')
body = body+echain+" & = "+eresultchain+"\\\\\n"
body = "" for n in range(21): a = random.choice([1, -1]) * random.randint(2, 9) b = random.choice([1, -1]) * random.randint(2, 9) c = random.choice([1, -1]) * random.randint(2, 9) d = random.choice([1, -1]) * random.randint(2, 9) e = (a*x+b)*(c*x+d) eresultchain = str(expand(e)) # on convertit le résultat en chaîne de caractères eresultchain = eresultchain.replace('**','^') # on met au format TeX les exposants eresultchain = eresultchain.replace('*','') # on élimine les symboles '*' echain = str(e) echain = echain.replace('*','') body = body+echain+" & = "+eresultchain+"\\\\\n"
body = ""

for n in range(21):
    a = random.choice([1, -1]) * random.randint(2, 9)
    b = random.choice([1, -1]) * random.randint(2, 9)
    c = random.choice([1, -1]) * random.randint(2, 9)
    d = random.choice([1, -1]) * random.randint(2, 9)
    e = (a*x+b)*(c*x+d)
    eresultchain = str(expand(e)) # on convertit le résultat en chaîne de caractères
    eresultchain = eresultchain.replace('**','^') # on met au format TeX les exposants
    eresultchain = eresultchain.replace('*','') # on élimine les symboles '*'
    echain = str(e)
    echain = echain.replace('*','')

    body = body+echain+" & = "+eresultchain+"\\\\\n"

Il est ici nécessaire d’anticiper sur la syntaxe LATEX pour remplacer certains caractères…

Écriture du fichier

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
container = start+body+end
file = "monfichier.tex"
if os.path.exists(file):
os.remove(file)
fichier = open("monfichier.tex","x") # "x" pour la création et l'écriture
fichier.write(container)
fichier.close()
container = start+body+end file = "monfichier.tex" if os.path.exists(file): os.remove(file) fichier = open("monfichier.tex","x") # "x" pour la création et l'écriture fichier.write(container) fichier.close()
container = start+body+end

file = "monfichier.tex"
if os.path.exists(file):
	os.remove(file)

fichier = open("monfichier.tex","x") # "x" pour la création et l'écriture
fichier.write(container)
fichier.close()

Compilation

Une fois le fichier créé, il est pratique de le compiler directement puis de l’afficher.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
instructions = "pdflatex "+file#"
os.system(instructions)
readpdf = "START "+file[:-4]+".pdf"
os.system(readpdf)
instructions = "pdflatex "+file#" os.system(instructions) readpdf = "START "+file[:-4]+".pdf" os.system(readpdf)
instructions = "pdflatex "+file#"
os.system(instructions)

readpdf = "START "+file[:-4]+".pdf"
os.system(readpdf)

Et voilà ! Une feuille d’exercices créée en à peine 2 secondes…

Le code complet

Le code complet ci-dessous:


5 1 vote
Évaluation de l'article
S’abonner
Notification pour
guest


3 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Commentaires en ligne
Afficher tous les commentaires
Axel Chambily

Bonjour, bien qu’abonné (et semble-t-il identifié) je ne parviens jamais à accéder aux « contenus réservés ». Comment se fait-ce ?

3
0
Nous aimerions avoir votre avis, veuillez laisser un commentaire.x