Advertisement
Toxotsist

Гайк 1

Mar 30th, 2022
979
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. from docx import *
  2. import codecs
  3. import datetime
  4. def parse():
  5.     file = codecs.open("data.txt", "r", "utf_8_sig")
  6.     a = file.readlines()
  7.     file.close()
  8.     keys = []
  9.     values = []
  10.  
  11.     d = {}
  12.     for line in a:
  13.         if line.find("{{"):
  14.             values.append(line.replace("\r\n", ""))
  15.         else:
  16.             keys.append(line.replace("\r\n", ""))
  17.     d = d.fromkeys(keys, 0)
  18.     i = 0
  19.  
  20.     for key in d.keys():
  21.         d[key] = values[i]
  22.         i += 1
  23.     d['{{DATE}}'] = str(datetime.datetime.today())
  24.     return d
  25.  
  26. def main():
  27.     template = 'template.docx'
  28.     result = 'result.docx'
  29.     data = parse()
  30.  
  31.     template_doc = Document(template)
  32.     for key, value in data.items():
  33.         for paragraph in template_doc.paragraphs:
  34.             replace_text(paragraph, key, value)
  35.  
  36.             for table in template_doc.tables:
  37.                 for row in table.rows:
  38.                     for cell in row.cells:
  39.                         replace_text(cell, key, value)
  40.             template_doc.save(result)
  41.  
  42. def replace_text(paragraph, key, value):
  43.     if key in paragraph.text:
  44.         paragraph.text = paragraph.text.replace(key, value)
  45. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement