''' Created on Jul 23, 2014 @author: Brett Paufler Copyright Brett Paufler Complete Refactor 9-8-15 Given a double line separated text file (in input directory) outputs HTML markup for img figcaption (to output directory and console display) EDIT FOR JOB SPECIFIC NEEDS IN: if __main__ == '__name__': ''' from os import listdir def caption(file_path_in, template='img', **kwargs): '''Converts a text file to html markup for sequential images. Two different layouts: figcaption img Numbers start at: digits = 1, 0 digits = 2, 00 digits = 3, 000 incrementing +1 per line in text file Blank lines in file separate <img> tags. New lines get <br> inserted Given: **kwargs passed per default_datum = { 'div_class': 'div_one', 'fig_class': 'fig_one', 'img_class': 'img_one', 'name': 'base_name', 'number': 'not passed', 'digits': 2, 'extension': 'jpg', 'alt': ' : Line Effect or Some Such', 'text': ' -- per input file --'} Spits Out: <div class="div_one"> <figure class="fig_one"> <img class="img_one" src="base_name_21.jpg" alt=" : Line Effect or Some Such"> <figcaption>I'm coming home </figcaption> </figure> </div> <br> <br> Or: <br><br> <img src="base_name_21.jpg" alt=" : Line Effect or Some Such" > <br><br>I'm coming home div_clas='', fig_class='', img_class='', name='', number='', digits=2, extension='', alt='', text='', ):''' #Talk About a Hack: kwargs = {'kwargs': {**kwargs}} or a nested dictionary datum = kwargs['kwargs'] #Additional Template Types Can Be Added Here if template == 'img': template = ('<br><br>\n<img\nsrc="{name}_{number}.{extension}"\nalt="{alt}"\n' + '>\n<br><br>{text}\n\n') elif template == 'fig': template = ('<div class="{div_class}">\n<figure class="{fig_class}">\n' + '<img class="{img_class}"\nsrc="{name}_{number}.{extension}"\n' + 'alt="{alt}">\n<figcaption>{text}\n</figcaption>\n</figure>\n</div>\n' + '<br>\n<br>\n\n\n') #Text preprocessing text_raw = open(file_path_in, 'r').read() text_list_in = text_raw.split('\n\n') text_list_in = [t.replace('\n', '<br>') for t in text_list_in] #Main Workhorse Engine text_out = '' for i, text_in in enumerate(text_list_in): datum['number'] = ('{:>0%d}' % datum['digits']).format(i) datum['text'] = text_in text_out += template.format(**datum) print text_out return text_out if __name__ == '__main__': #BULK of EDITING IN default_datum #Numbers start at 00 #digits 2 == 00, 01, 02, etc default_datum = { 'div_class': 'div_one', 'fig_class': 'fig_one', 'img_class': 'img_one', 'name': 'exodus', 'number': 'not passed', 'digits': 2, 'extension': 'jpg', 'alt': ' - Tals of the Nav - Revised Line Effect', 'text': ' -- per input file --'} dir_in = './input/' for text_file in listdir(dir_in): iN = dir_in + text_file sN = iN.replace('input', 'output') #template = 'fig' or 'img' should be all that needs editing here text_out = caption(file_path_in=iN, template='img', kwargs=default_datum) with open(sN, 'w') as f: f.write(text_out)