#!/usr/bin/python3.4 # coding=utf-8 # $Id$ # $HeadURL$ """For parsing MediaWiki text, we rely on the package mwparserfromhell (https://github.com/earwig/mwparserfromhell). This module just contains a few additional useful functions. Other Python MediaWiki parsers: * py-wikimarkup https://github.com/dcramer/py-wikimarkup * mwlib http://code.pediapress.com/wiki/wiki * https://www.mediawiki.org/wiki/Alternative_parsers """ class ParseError(RuntimeError): """Exception used by some of the functions""" pass def template_to_table(template, keylen=None): """Reformat the given template to be tabular. >>> template {{foo|bar|bazz=7}} >>> template_to_table(template) {{foo | bar | bazz = 7 }} :param keylen: length of the keys or None for automatic determination """ if keylen is None: shown_keys = [len(param.name.strip()) for param in template.params if param.showkey] keylen = max(shown_keys) if shown_keys else 0 template.name = '{}\n'.format(template.name.strip()) for param in template.params: if param.showkey: param.name = ' {{:{}}} '.format(keylen).format(param.name.strip()) value = param.value.strip() if len(value) > 0: param.value = ' {}\n'.format(value) else: param.value = '\n'