Sweetohm

Michel Casabianca

J’ai eu aujourd’hui à générer un document Mardown qui comportait des tableaux. Voici le code qui génère le tableau au format Markdown à partir d’une liste des en-têtes de colonnes et d’une liste de lignes :

#!/usr/bin/env python
# encoding: UTF-8


def markdown_table(heads, cells):
    def to_unicode(thing):
        if hasattr(thing, '__iter__'):
            return [to_unicode(e) for e in thing]
        else:
            return unicode(str(thing), 'UTF-8')
    def row_width(row):
        return max([len(e) for e in row])
    heads = to_unicode(heads)
    cells = to_unicode(cells)
    width = max(row_width(heads), 
                max([row_width(l) for l in cells]))
    table = u'| ' + u' | '.join([h.ljust(width, ' ') for h in heads]) + u' |'
    table += u'\n|-' + u'-|-'.join(['-'*width for _ in range(len(heads))]) + u'-|'
    for line in cells:
        table += u'\n| ' + u' | '.join([e.ljust(width, ' ') for e in line]) + u' |'
    return table


if __name__ == '__main__':
    headers = ('foo', 'bar')
    lines = ((1, 2), (3, 4), ('éèêë', 'îïôœ'))
    table = markdown_table(headers, lines)
    print(table.encode('UTF-8'))

Enjoy!