Пип, что не так с этим скриптом [закрыто]Python

Программы на Python
Ответить
Anonymous
 Пип, что не так с этим скриптом [закрыто]

Сообщение Anonymous »

Что не так с этим кодом? Пытаясь изменить документ, я пытаюсь создать файл, который автоматически заменяет слова на вводимые пользователем слова.
Я вставил свой код того, что пробовал до сих пор. Что здесь изменить? При запуске не создается выходной файл, но и не отображается никаких ошибок.
Добавляю ли я еще проверки ошибок, чтобы выяснить, что происходит не так?
from docx import Document
from datetime import datetime
import os

# --- collect inputs ---
print("G-Mob Document Generator")
print("-" * 40)
pod_name = input("Pod / instance name (e.g. ATN77): ").strip()
ip = input("IP address: ").strip()

# --- build the replacement map ---
# order matters: longer / more specific keys must come BEFORE shorter ones
# that are a substring of them, otherwise the shorter one will match first
# and corrupt the longer one.
gtm_region_value = f"AON-{pod_name}_DNS"

replacements = {
"v_Mgmt_IP_Address_XX": ip,
"v_Mgmt_IP_Address": ip,
"v_GTM_subnet": ip,
"v_GTM_Region": gtm_region_value,
}

# --- helper: replace inside a paragraph while preserving formatting ---
def replace_in_paragraph(paragraph, replacements):
# Join all runs, do the replacement on the full text, then push it back
# into the first run and blank out the rest. This loses per-run formatting
# WITHIN the paragraph but keeps paragraph-level formatting intact, which
# is fine for placeholder tokens that aren't individually styled.
full_text = "".join(run.text for run in paragraph.runs)
if not any(key in full_text for key in replacements):
return
new_text = full_text
for key, val in replacements.items():
new_text = new_text.replace(key, val)
if paragraph.runs:
paragraph.runs[0].text = new_text
for run in paragraph.runs[1:]:
run.text = ""

# --- walk the document ---
doc = Document("template.docx")

# body paragraphs
for paragraph in doc.paragraphs:
replace_in_paragraph(paragraph, replacements)

# paragraphs inside tables (G-Mob docs almost always have tables)
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
for paragraph in cell.paragraphs:
replace_in_paragraph(paragraph, replacements)

# headers and footers
for section in doc.sections:
for hf in (section.header, section.footer):
for paragraph in hf.paragraphs:
replace_in_paragraph(paragraph, replacements)

# --- save ---
os.makedirs("output", exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
out_path = f"output/gmob_{pod_name}_{stamp}.docx"
doc.save(out_path)

print(f"\nDone. Saved to: {out_path}")
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»