「乱搞」用 Python 处理 word 文档

发布时间 2023-09-15 12:06:56作者: Luckyblock

写在前面

大家好啊,我是过气 up 主 Luckyblock,今天给大家来点想看的东西。

简单记录如何使用 Python 中的 python-docx 模块快速处理 word 文档。

周末就是省赛了,然而板子还没整合起来。因为我是一个懒狗,懒得把代码再慢慢复制进文档里了,于是来学了这个。

osu 好玩。

我是飞舞、、、

主要参考:https://python-docx.readthedocs.io/en/latest/index.html

代码

因为太简单了懒得记录了,直接看参考文档罢。

import os
from docx import Document
from docx.shared import Inches

document = Document()
root = os.path.abspath('.')
acm = os.path.join(os.path.join(root, 'ACM'), '模板')

def add_file(title_, path_):
  document.add_heading(title_, level=2)
  with open(path_, "r", encoding='utf-8', errors = 'ignore') as f:
    document.add_paragraph(f.read())
    document.add_paragraph()
  

def solve(title_, path_):
  document.add_page_break()
  document.add_heading(title_, level=1)
  for file in os.listdir(path_):
    add_file(file, os.path.join(path_, file))

document.add_heading('Luckyblock 自用向模板库 ver0.2', 0)
bakushino = document.add_picture(os.path.join(root, 'bakushino.png'), width = Inches(5.0))

for category in os.listdir(acm):
  pos = os.path.join(acm, category)
  if not os.path.isdir(pos):
    continue
  solve(category, pos)

document.save('模板.docx')

写在最后

参考: