Что не так с этим кодом? Пытаясь изменить документ, я пытаюсь создать файл, который автоматически заменяет слова на вводимые пользователем слова.
Я вставил свой код того, что пробовал до сих пор. Что здесь изменить? При запуске не создается выходной файл, но и не отображается никаких ошибок.
Добавляю ли я еще проверки ошибок, чтобы выяснить, что происходит не так?
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}")
Пип, что не так с этим скриптом [закрыто] ⇐ Python
Программы на Python
1778603180
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}")
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия