Zhuge Liang was studying Python in his study when Ma Su rushed in.
Ma Su: “Strategist, I have a problem! I have to write a large number of military reports every day, and organizing the data is driving me crazy.”
Zhuge Liang: “Oh? Let me guess, you need to organize the battle report data into a document?”
Ma Su: “Exactly! I have to copy and paste manually every time, it’s too troublesome. Strategist, do you have a good solution?”
Zhuge Liang: “Yes! Python is your powerful assistant. Today I will teach you how to automatically generate documents using Python, so you can say goodbye to the troubles of copying and pasting.”
Zhuge Liang: “First, let’s see how to prepare the data. Suppose we have some military data to organize:”
# Create example data
battle_data = {
"date": "Year of Jianxing 3",
"location": "Jieting",
"our_troops": 5000,
"enemy_troops": 8000,
"battle_situation": ["First day clash", "Second day raid", "Third day retreat"]
}
Ma Su: “Wow! This is exactly the data format we usually record, right?”
Zhuge Liang: “That’s right! Next, we will use python-docx to generate the document. First, install it:”
from docx import Document
from docx.shared import Inches
# Create a new document
doc = Document()
doc.add_heading('Battle Report of Jieting', 0)
# Add basic information
doc.add_paragraph(f"Battle Date: {battle_data['date']}")
doc.add_paragraph(f"Battle Location: {battle_data['location']}")
# Add a troop comparison table
table = doc.add_table(rows=1, cols=2)
table.style = 'Table Grid'
header_cells = table.rows[0].cells
header_cells[0].text = 'Our Troops'
header_cells[1].text = 'Enemy Troops'
row_cells = table.add_row().cells
row_cells[0].text = str(battle_data['our_troops'])
row_cells[1].text = str(battle_data['enemy_troops'])
# Save the document
doc.save('battle_report.docx')
Ma Su: “That’s amazing! This automatically generates the document?”
Zhuge Liang: “Not only that, we can also add an analysis of the battle situation:”
# Add battle situation analysis
doc.add_heading('Battle Situation Analysis', level=1)
for day in battle_data['battle_situation']:
doc.add_paragraph(day, style='List Bullet')
# Add summary
doc.add_paragraph('Summary: Lessons learned from this battle...', style='Intense Quote')
Ma Su: “Wonderful! This report looks very professional!”
Zhuge Liang: “If there are multiple reports to generate, we can do it like this:”
def generate_report(battle_data, filename):
doc = Document()
doc.add_heading(f'{battle_data["location"]} Battle Report', 0)
# ... previous code logic ...
doc.save(filename)
return f"Report {filename} generated successfully!"
# Batch process multiple battle data
battles = [battle_data, battle_data2, battle_data3] # Assume multiple battle data
for i, battle in enumerate(battles):
generate_report(battle, f'battle_report_{i+1}.docx')
Ma Su: “That’s awesome! Now I don’t have to organize manually anymore. But strategist, I need to remember these codes well.”
Zhuge Liang: “You can be taught! Remember one thing: The key to automation is templating and standardization. First, define the data structure well, then design the document template, and finally elegantly combine them using Python.”
Ma Su: “Got it! I will go practice now!”
Zhuge Liang: “Wait! Before you go, let me give you a little tip: remember to handle exceptions to avoid program errors:”
try:
generate_report(battle_data, 'report.docx')
except Exception as e:
print(f"Error generating report: {str(e)}")
else:
print("Report generated successfully!")
Ma Su: “Thank you, strategist! Now I can say goodbye to the troubles of copying and pasting!”
Zhuge Liang: “Go! Remember: Python is not just a tool; it is your powerful assistant. Use it well, and it will help you achieve twice the result with half the effort!”