Skip to content

Instantly share code, notes, and snippets.

@JustusAdam
Last active August 29, 2015 14:26
Show Gist options
  • Save JustusAdam/8b4e2ed5350d1af9e270 to your computer and use it in GitHub Desktop.
Save JustusAdam/8b4e2ed5350d1af9e270 to your computer and use it in GitHub Desktop.
What I use to format personalised bulk mails. Works on any text though.
#!/usr/bin/env python3
from string import Template
import sys
import collections
import pathlib
def from_yaml(file):
import yaml
return yaml.load(file)
def from_json(file):
import json
return json.load(file)
loader = {
'yaml': from_yaml,
'yml': from_yaml,
'json': from_json
}
def format_letters(letter_template_raw, name_template_raw, data):
has_def = 'defaults' in data and 'values' in data
if has_def:
defaults = data['defaults']
values = data['values']
else:
values = data
letter_template = Template(letter_template_raw)
name_template = Template(name_template_raw)
def format_one(instance):
if has_def:
instance = collections.ChainMap(instance, defaults)
return name_template.substitute(instance), letter_template.substitute(instance)
return map(format_one, values)
def main():
_, letter_file, data_file, output_format = sys.argv
with open(letter_file, 'r') as f:
letter = f.read()
with open(data_file) as f:
_, ext = data_file.rsplit('.', 1)
data = loader.get(ext, from_yaml)(f)
for name, value in format_letters(letter, output_format, data):
path = pathlib.Path(name)
if not path.parent.exists():
path.parent.mkdir(parents=True)
with path.open('w+') as f:
print(value, file=f)
# invoke with `./format_letter letter testdata.yaml output/letter-to-\${name}`
if __name__ == '__main__':
main()
Dear $greeting $title $name,
You are hereby invited to my party
$extra
Sincerely yours
Justus
# Example for how the data file might look
defaults:
title: Dr.
greeting: Mr.
extra: ""
values:
-
title: ""
name: Arthur
-
name: Maria
greeting: Mrs.
extra: Bring the kids as well.
# if you do not have defaults you can also omit the 'defaults' and 'values' key and just list the values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment