如何向Word文档标题添加文本

问题描述 投票:0回答:1

Header 我正在尝试将“改编的证明”文本添加到我的 .docx 文档的标题中。我想在“Instruções:”之后添加此文本,但是,我相信我以错误的方式传递它,并且代码在文本中找不到这个词“Instruções:”。如果我将“说明”一词放置在文档中的其他位置,则会附加文本“改编证明”。

import os
import shutil
from docx import Document
import requests
from senhaapi import API_KEY
import json
from docxtpl import DocxTemplate

ans = read_multiple_choice(
    "Escolha a matéria da prova que será submetida",
    [{"label": "Português", "value": "portugues"},
     {"label": "Matemática", "value": "matematica"},
     {"label": "Geografia", "value": "geografia"},
     {"label": "História", "value": "historia"},
     {"label": "Física", "value": "fisica"},
     {"label": "Química", "value": "quimica"},
     {"label": "Literatura", "value": "Literatura"},
     {"label": "Inglês", "value": "ingles"},
     {"label": "Espanhol", "value": "espanhol"}, ],
)

if ans == "portugues":
    file_response = read_file("Enviar")
    file_name = file_response.name

    if not file_name.endswith(".docx"):
        display("A prova enviada deve estar no formato .docx", size='medium')
    else:
        script_dir = os.getcwd()
        destination_dir = os.path.join(script_dir, "foo/bar")
        os.makedirs(destination_dir, exist_ok=True)
        original_file_path = os.path.join(destination_dir, file_name)
        with open(original_file_path, "wb") as destination_file:
            shutil.copyfileobj(file_response.file, destination_file)

        document = Document(original_file_path)

        texto_a_adicionar = "Prova Adaptada"

        for paragraph in document.paragraphs:
            if not paragraph.text.strip():  # Verificar se o parágrafo está vazio
                paragraph.add_run(texto_a_adicionar)
                break  # Parar após adicionar o texto

        modified_file_path = os.path.join(destination_dir, "modified_" + file_name)
        document.save(modified_file_path)

else:
    display("Selecione uma opção válida", size='medium')

包含file_responder、display、read_multiple_choice的部分来自我的工作库并且工作正常。 我很感激你的帮助

python docx
1个回答
0
投票

您当前的代码是将文本添加到文档正文中的段落而不是标题中。

我找到了通过 python-docx 库修复的方法:

import os
import shutil
from docx import Document
from docx.oxml.ns import qn
from docx.shared import Pt
from docxtpl import DocxTemplate
from senhaapi import API_KEY  # You need to import your API key module here
from your_library import read_multiple_choice, read_file, display  # Import your library functions here

ans = read_multiple_choice(
    "Escolha a matéria da prova que será submetida",
    [{"label": "Português", "value": "portugues"},
     {"label": "Matemática", "value": "matematica"},
     # ... other options ...
     {"label": "Espanhol", "value": "espanhol"},],
)

if ans == "portugues":
    file_response = read_file("Enviar")
    file_name = file_response.name

    if not file_name.endswith(".docx"):
        display("A prova enviada deve estar no formato .docx", size='medium')
    else:
        script_dir = os.getcwd()
        destination_dir = os.path.join(script_dir, "foo/bar")
        os.makedirs(destination_dir, exist_ok=True)
        original_file_path = os.path.join(destination_dir, file_name)
        with open(original_file_path, "wb") as destination_file:
            shutil.copyfileobj(file_response.file, destination_file)

        document = Document(original_file_path)
        
        texto_a_adicionar = "Adapted Proof"

        # Iterate through all sections and headers to find "Instruções:" and modify the header
        for section in document.sections:
            header = section.header
            for paragraph in header.paragraphs:
                if "Instruções:" in paragraph.text:
                    run = paragraph.add_run(texto_a_adicionar)
                    font = run.font
                    font.size = Pt(12)  # Set the font size as needed
                    break  # Stop after modifying the header

        modified_file_path = os.path.join(destination_dir, "modified_" + file_name)
        document.save(modified_file_path)

else:
    display("Selecione uma opção válida", size='medium')
 

用你的库替换 your_library 我认为 python-docx 是一个很好的方法,但你可能正在寻找其他东西祝你好运希望我的代码适合你

© www.soinside.com 2019 - 2024. All rights reserved.