# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from future.utils import raise_from, string_types from builtins import (bytes, str, open, super, range, zip, round, input, int, pow, object) import io import re import traceback from itertools import chain import gslab_make.private.messages as messages from gslab_make.private.exceptionclasses import CritError, ColoredError from gslab_make.private.utility import convert_to_list, norm_path, format_message def _parse_tag(tag): """.. Parse tag from input.""" if not re.match('\n', tag, flags = re.IGNORECASE): raise Exception else: tag = re.sub('\n', r'\g<1>', tag, flags = re.IGNORECASE) tag = tag.lower() return(tag) def _parse_data(data, null): """.. Parse data from input. Parameters ---------- data : list Input data to parse. null : str String to replace null characters. Returns ------- data : list List of data values from input. """ null_strings = ['', '.', 'NA'] data = [row.rstrip('\r\n') for row in data] data = [row for row in data if row] data = [row.split('\t') for row in data] data = chain(*data) data = list(data) data = [null if value in null_strings else value for value in data] return(data) def _parse_content(file, null): """.. Parse content from input.""" with io.open(file, 'r', encoding = 'utf-8') as f: content = f.readlines() try: tag = _parse_tag(content[0]) except: raise_from(CritError(messages.crit_error_no_tag % file), None) data = _parse_data(content[1:], null) return(tag, data) def _insert_value(line, value, type, null): """.. Insert value into line. Parameters ---------- line : str Line of document to insert value. value : str Value to insert. type : str Formatting for value. Returns ------- line : str Line of document with inserted value. """ if (type == 'no change'): line = re.sub('\\\\?#\\\\?#\\\\?#', value, line) elif (type == 'round'): if value == null: line = re.sub('(.*?)\\\\?#[0-9]+\\\\?#', r'\g<1>' + value, line) else: try: value = float(value) except: raise_from(CritError(messages.crit_error_not_float % value), None) digits = re.findall('\\\\?#([0-9]+)\\\\?#', line)[0] rounded_value = format(value, '.%sf' % digits) line = re.sub('(.*?)\\\\?#[0-9]+\\\\?#', r'\g<1>' + rounded_value, line) elif (type == 'comma + round'): if value == null: line = re.sub('(.*?)\\\\?#[0-9]+,\\\\?#', r'\g<1>' + value, line) else: try: value = float(value) except: raise_from(CritError(messages.crit_error_not_float % value), None) digits = re.findall('\\\\?#([0-9]+),\\\\?#', line)[0] rounded_value = format(value, ',.%sf' % digits) line = re.sub('(.*?)\\\\?#[0-9]+,\\\\?#', r'\g<1>' + rounded_value, line) return(line) def _insert_tables_lyx(template, tables, null): """.. Fill tables for LyX template. Parameters ---------- template : str Path of LyX template to fill. tables : dict Dictionary ``{tag: values}`` of tables. Returns ------- template : str Filled LyX template. """ with io.open(template, 'r', encoding = 'utf-8') as f: doc = f.readlines() is_table = False for i in range(len(doc)): # Check if table if not is_table and re.match('name "tab:', doc[i]): tag = doc[i].replace('name "tab:','').rstrip('"\n').lower() try: values = tables[tag] entry_count = 0 is_table = True except KeyError: raise_from(CritError(messages.crit_error_no_input_table % tag), None) # Fill in values if table if is_table: try: if re.match('.*###', doc[i]): doc[i] = _insert_value(doc[i], values[entry_count], 'no change', null) entry_count += 1 elif re.match('.*#[0-9]+#', doc[i]): doc[i] = _insert_value(doc[i], values[entry_count], 'round', null) entry_count += 1 elif re.match('.*#[0-9]+,#', doc[i]): doc[i] = _insert_value(doc[i], values[entry_count], 'comma + round', null) entry_count += 1 elif re.match('', doc[i]): is_table = False if entry_count != len(values): raise_from(CritError(messages.crit_error_too_many_values % tag), None) except IndexError: raise_from(CritError(messages.crit_error_not_enough_values % tag), None) doc = '\n'.join(doc) return(doc) def _insert_tables_latex(template, tables, null): """.. Fill tables for LaTeX template. Parameters ---------- template : str Path of LaTeX template to fill. tables : dict Dictionary ``{tag: values}`` of tables. Returns ------- template : str Filled LaTeX template. """ with io.open(template, 'r', encoding = 'utf-8') as f: doc = f.readlines() is_table = False for i in range(len(doc)): # Check if table if not is_table and re.search('label\{tab:', doc[i]): tag = doc[i].split(':')[1].rstrip('}\n').strip('"').lower() try: values = tables[tag] entry_count = 0 is_table = True except KeyError: raise_from(CritError(messages.crit_error_no_input_table % tag), None) # Fill in values if table if is_table: try: line = doc[i].split("&") for j in range(len(line)): if re.search('.*\\\\#\\\\#\\\\#', line[j]): line[j] = _insert_value(line[j], values[entry_count], 'no change', null) entry_count += 1 elif re.search('.*\\\\#[0-9]+\\\\#', line[j]): line[j] = _insert_value(line[j], values[entry_count], 'round', null) entry_count += 1 elif re.search('.*\\\\#[0-9]+,\\\\#', line[j]): line[j] = _insert_value(line[j], values[entry_count], 'comma + round', null) entry_count += 1 doc[i] = "&".join(line) if re.search('end\{tabular\}', doc[i], flags = re.IGNORECASE): is_table = False if entry_count != len(values): raise_from(CritError(messages.crit_error_too_many_values % tag), None) except IndexError: raise_from(CritError(messages.crit_error_not_enough_values % tag), None) doc = '\n'.join(doc) return(doc) def _insert_tables(template, tables, null): """.. Fill tables for template. Parameters ---------- template : str Path of template to fill. tables : dict Dictionary ``{tag: values}`` of tables. Returns ------- template : str Filled template. """ template = norm_path(template) if re.search('\.lyx', template): doc = _insert_tables_lyx(template, tables, null) elif re.search('\.tex', template): doc = _insert_tables_latex(template, tables, null) return(doc) def tablefill(inputs, template, output, null = '.'): """.. Fill tables for template using inputs. Fills tables in document ``template`` using files in list ``inputs``. Writes filled document to file ``output``. Null characters in ``inputs`` are replaced with value ``null``. Parameters ---------- inputs : list Input or list of inputs to fill into template. template : str Path of template to fill. output : str Path of output. null : str Value to replace null characters (i.e., ``''``, ``'.'``, ``'NA'``). Defaults to ``'.'``. Returns ------- None Example ------- .. code-block:: ################################################################# # tablefill_readme.txt - Help/Documentation for tablefill.py ################################################################# Description: tablefill.py is a Python module designed to fill LyX/Tex tables with output from text files (usually output from Stata or Matlab). Usage: Tablefill takes as input a LyX (or Tex) file containing empty tables (the template file) and text files containing data to be copied to these tables (the input files), and produces a LyX (or Tex) file with filled tables (the output file). For brevity, LyX will be used to denote LyX or Tex files throughout. Tablefill must first be imported to make.py. This is typically achieved by including the following lines: ``` from gslab_fill.tablefill import tablefill ``` Once the module has been imported, the syntax used to call tablefill is as follows: ``` tablefill(input = 'input_file(s)', template = 'template_file', output = 'output_file') ``` The argument 'template' is the user written LyX file which contains the tables to be filled in. The argument 'input' is a list of the text files containing the output to be copied to the LyX tables. If there are multiple input text files, they are listed as: input = 'input_file_1 input_file_2'. The argument 'output' is the name of the filled LyX file to be produced. Note that this file is created by tablefill.py and should not be edited manually by the user. ########################### Input File Format: ########################### The data needs to be tab-delimited rows of numbers (or characters), preceeded by `