import os, sys, csv, re, unicodedata def slugify(value, allow_unicode=False): """ Taken from https://github.com/django/django/blob/master/django/utils/text.py Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace, dashes, and underscores. """ value = str(value) if allow_unicode: value = unicodedata.normalize('NFKC', value) else: value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = re.sub(r'[^\w\s-]', '', value) return value.strip() with open("5etools-spells.csv", encoding='utf-8') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') headers = next(reader) print(headers) csv_spells={} for data in reader: csv_spells[data[0]] = {} for i,key in enumerate(headers): csv_spells[data[0]][key] = data[i] with open("5etools-spells.md", encoding='utf-8') as mdfile: text = mdfile.read().split('\n#### ') for para in text: if not para: continue spell = {} preamble, spell['text'] = para.split('\n---\n') spell['name'] = preamble.split('\n')[0] spell_c = csv_spells[spell['name']] spell['casting'] = spell_c['Casting Time'] spell['mats'] = spell_c['Components'].split(' (')[0] spell['level'] = 0 if spell_c['Level'] == 'Cantrip' else int(spell_c['Level'][0]) tags = [spell_c['School']] if 'concentration' in spell_c['Duration'].lower(): tags.append('Concentration') if 'ritual' in preamble.split('\n')[1].lower(): tags.append('Ritual') spell['tags'] = ", ".join(tags) spell['classes'] = ", ".join(set([c.strip() for c in spell_c['Classes'].replace('(Revisited)','').split(', ')])) spell['priced'] = 'true' if 'worth' in spell_c['Components'].lower() else 'false' spell['consumed'] = 'true' if 'consume' in spell_c['Components'].lower() else 'false' spell['upcasttag'] = 'true' if bool(spell_c['At Higher Levels']) else 'false' spell['book'] = spell_c['Source'] cardtxt = """--- level: {level} components: [{mats}] material: {priced} consumed: {consumed} cast_time: {casting} upcast: {upcasttag} classes: [{classes}] tags: [{tags}] --- #### {} *{book}* """.format(para,**spell) if not os.path.exists('spells'): os.mkdir('spells') src_path = os.path.join('spells', spell['book']) if not os.path.exists(src_path): os.mkdir(src_path) card_path = os.path.join(src_path, slugify(spell['name'])+'.md') with open(card_path, 'w') as fileout: fileout.write(cardtxt)