Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from docx import *
- import codecs
- import datetime
- def parse():
- file = codecs.open("data.txt", "r", "utf_8_sig")
- a = file.readlines()
- file.close()
- keys = []
- values = []
- d = {}
- for line in a:
- if line.find("{{"):
- values.append(line.replace("\r\n", ""))
- else:
- keys.append(line.replace("\r\n", ""))
- d = d.fromkeys(keys, 0)
- i = 0
- for key in d.keys():
- d[key] = values[i]
- i += 1
- d['{{DATE}}'] = str(datetime.datetime.today())
- return d
- def main():
- template = 'template.docx'
- result = 'result.docx'
- data = parse()
- template_doc = Document(template)
- for key, value in data.items():
- for paragraph in template_doc.paragraphs:
- replace_text(paragraph, key, value)
- for table in template_doc.tables:
- for row in table.rows:
- for cell in row.cells:
- replace_text(cell, key, value)
- template_doc.save(result)
- def replace_text(paragraph, key, value):
- if key in paragraph.text:
- paragraph.text = paragraph.text.replace(key, value)
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement