What are some approaches to outputting a Python data structure to reStructuredText

后端 未结 6 562
星月不相逢
星月不相逢 2020-12-31 18:21

I have a list of tuples in Python that I would like to output to a table in reStructuredText.

The docutils library has great support for converting reStructuredText

6条回答
  •  萌比男神i
    2020-12-31 19:17

    >> print make_table([['Name', 'Favorite Food', 'Favorite Subject'],
                         ['Joe', 'Hamburgers', 'Cars'],
                         ['Jill', 'Salads', 'American Idol'],
                         ['Sally', 'Tofu', 'Math']])
    
    +------------------+------------------+------------------+
    | Name             | Favorite Food    | Favorite Subject |
    +==================+==================+==================+
    | Joe              | Hamburgers       | Cars             |
    +------------------+------------------+------------------+
    | Jill             | Salads           | American Idol    |
    +------------------+------------------+------------------+
    | Sally            | Tofu             | Math             |
    +------------------+------------------+------------------+
    

    Here is the code I use for quick and dirty reStructuredText tables:

    def make_table(grid):
        cell_width = 2 + max(reduce(lambda x,y: x+y, [[len(item) for item in row] for row in grid], []))
        num_cols = len(grid[0])
        rst = table_div(num_cols, cell_width, 0)
        header_flag = 1
        for row in grid:
            rst = rst + '| ' + '| '.join([normalize_cell(x, cell_width-1) for x in row]) + '|\n'
            rst = rst + table_div(num_cols, cell_width, header_flag)
            header_flag = 0
        return rst
    
    def table_div(num_cols, col_width, header_flag):
        if header_flag == 1:
            return num_cols*('+' + (col_width)*'=') + '+\n'
        else:
            return num_cols*('+' + (col_width)*'-') + '+\n'
    
    def normalize_cell(string, length):
        return string + ((length - len(string)) * ' ')
    

提交回复
热议问题