Exemple de formule : $E = mc^2$ ou $$\frac{a}{b} = \sqrt{x}$$
📋 Aperçu du contenu détecté :
from docx import Document
from docx.shared import Pt, RGBColor, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
import redef parse_markdown_table(table_text):
“””Parse a markdown table into rows and columns”””
lines = [line.strip() for line in table_text.strip().split(‘\n’) if line.strip()]
if len(lines) < 2:
return []
# Remove separator line
rows = [lines[0]] + lines[2:]
parsed_rows = []
for row in rows:
cells = [cell.strip() for cell in row.split('|')]
cells = [c for c in cells if c] # Remove empty cells
if cells:
parsed_rows.append(cells)
return parsed_rowsdef convert_latex_to_word_equation(latex_text):
"""Convert LaTeX math to Word OMML format (simplified)"""
# This is a simplified conversion - for complex formulas, you may need additional libraries
latex_text = latex_text.strip('$').strip()
# Basic conversions
conversions = {
r'\frac': '/',
r'\times': '×',
r'\div': '÷',
r'\pm': '±',
r'\leq': '≤',
r'\geq': '≥',
r'\neq': '≠',
r'\sqrt': '√',
r'\sum': '∑',
r'\int': '∫',
r'\infty': '∞',
r'\alpha': 'α',
r'\beta': 'β',
r'\gamma': 'γ',
r'\delta': 'δ',
r'\pi': 'π',
r'\theta': 'θ',
r'\lambda': 'λ',
r'\mu': 'μ',
r'\sigma': 'σ',
}
result = latex_text
for latex, symbol in conversions.items():
result = result.replace(latex, symbol)
# Remove common LaTeX commands
result = re.sub(r'\\[a-zA-Z]+', '', result)
result = result.replace('{', '').replace('}', '')
return resultdef process_text_with_math(text, paragraph):
"""Process text that may contain inline math formulas"""
# Match LaTeX formulas: $...$ or $$...$$
pattern = r'\$\$(.+?)\$\$|\$(.+?)\$'
last_end = 0
for match in re.finditer(pattern, text):
# Add text before formula
if match.start() > last_end:
paragraph.add_run(text[last_end:match.start()])
# Add formula (converted)
formula = match.group(1) or match.group(2)
formula_run = paragraph.add_run(convert_latex_to_word_equation(formula))
formula_run.italic = True
formula_run.font.color.rgb = RGBColor(0, 0, 128)
last_end = match.end()
# Add remaining text
if last_end < len(text):
paragraph.add_run(text[last_end:])def convert_ai_text_to_word(input_text, output_filename="document_converti.docx"):
"""Convert AI-generated text (with tables and formulas) to Word document"""
doc = Document()
# Add title
title = doc.add_heading('Document Converti depuis IA', 0)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# Split text into blocks
blocks = input_text.split('\n\n')
i = 0
while i < len(blocks):
block = blocks[i].strip()
if not block:
i += 1
continue
# Detect and process tables
if '|' in block and block.count('|') > 2:
# Check if it’s a markdown table
lines = block.split(‘\n’)
if any(‘—‘ in line or ‘===’ in line for line in lines):
# This is a table
table_data = parse_markdown_table(block)
if table_data:
# Create Word table
table = doc.add_table(rows=len(table_data), cols=len(table_data[0]))
table.style = ‘Light Grid Accent 1’
for row_idx, row_data in enumerate(table_data):
for col_idx, cell_data in enumerate(row_data):
cell = table.rows[row_idx].cells[col_idx]
# Process cell content for formulas
if ‘$’ in cell_data:
process_text_with_math(cell_data, cell.paragraphs[0])
else:
cell.text = cell_data
# Bold header row
if row_idx == 0:
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.bold = True
doc.add_paragraph() # Add space after table
i += 1
continue
# Detect headings
if block.startswith(‘#’):
level = len(block) – len(block.lstrip(‘#’))
heading_text = block.lstrip(‘#’).strip()
doc.add_heading(heading_text, level=min(level, 3))
# Detect bullet points
elif block.startswith(‘-‘) or block.startswith(‘*’) or block.startswith(‘•’):
lines = block.split(‘\n’)
for line in lines:
clean_line = line.lstrip(‘-*•’).strip()
if clean_line:
p = doc.add_paragraph(style=’List Bullet’)
process_text_with_math(clean_line, p)
# Detect numbered lists
elif re.match(r’^\d+\.’, block):
lines = block.split(‘\n’)
for line in lines:
clean_line = re.sub(r’^\d+\.\s*’, ”, line).strip()
if clean_line:
p = doc.add_paragraph(style=’List Number’)
process_text_with_math(clean_line, p)
# Regular paragraph with potential formulas
else:
p = doc.add_paragraph()
process_text_with_math(block, p)
i += 1
# Save document
doc.save(output_filename)
return output_filename# Example with tables and mathematical formulas
example_text = “””# Rapport Scientifique## IntroductionVoici un exemple de conversion avec des formules mathématiques et des tableaux.## Formules MathématiquesL’équation quadratique est donnée par $ax^2 + bx + c = 0$ et sa solution est:$$x = \\frac{-b \\pm \\sqrt{b^2 – 4ac}}{2a}$$La formule d’Einstein: $E = mc^2$Intégrale: $\\int_0^\\infty e^{-x} dx = 1$## Tableau de Données| Nom | Âge | Score | Formule |
|—–|—–|——-|———|
| Alice | 25 | 95 | $x^2 + 2x$ |
| Bob | 30 | 87 | $\\sqrt{x}$ |
| Charlie | 28 | 92 | $\\pi r^2$ |## Tableau de Résultats| Expérience | Valeur | Écart-type | P-value |
|————|——–|————|———|
| Test A | 12.5 | $\\pm 0.3$ | < 0.05 |
| Test B | 15.8 | $\\pm 0.5$ | < 0.01 |
| Test C | 10.2 | $\\pm 0.2$ | < 0.001 |## ConclusionLes résultats montrent que $\\alpha = 0.05$ est significatif.- Point important avec formule: $\\theta = 45°$
- Autre observation: $\\lambda = 550 nm$
- Résultat final: $\\sigma = 2.3$
"""# Create the document
output_file = convert_ai_text_to_word(example_text)
print(f"Document créé: {output_file}")
Convertisseur IA vers Word
📄 Convertisseur IA → Word
Transformez vos textes de ChatGPT, Claude, Grok en documents Word professionnels