8

我有一个 Python 中的元组列表,我想将其输出到 reStructuredText 中的表中。

docutils库对将reStructuredText转换为其他格式有很好的支持,但我想直接从内存中的数据结构写入reStructuredText。

4

6 回答 6

9

查看表格包。它可以通过以下方式输出 RST 格式:

print tabulate(table, headers, tablefmt="rst")
于 2015-03-04T13:36:10.770 回答
6
>> 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             |
+------------------+------------------+------------------+

这是我用于快速和肮脏的 reStructuredText 表的代码:

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)) * ' ')
于 2012-09-21T22:44:27.973 回答
5

我不知道有任何库可以从 python 数据结构输出 RST,但是自己格式化很容易。这是将 python 元组列表格式化为 RST 表的示例:

>>> data = [('hey', 'stuff', '3'),
            ('table', 'row', 'something'),
            ('xy', 'z', 'abc')]
>>> numcolumns = len(data[0])
>>> colsizes = [max(len(r[i]) for r in data) for i in range(numcolumns)]
>>> formatter = ' '.join('{:<%d}' % c for c in colsizes)
>>> rowsformatted = [formatter.format(*row) for row in data]
>>> header = formatter.format(*['=' * c for c in colsizes])
>>> output = header + '\n' + '\n'.join(rowsformatted) + '\n' + header
>>> print output
===== ===== =========
hey   stuff 3        
table row   something
xy    z     abc      
===== ===== =========
于 2012-07-05T18:49:11.287 回答
2

@cieplak 的回答很棒。我对其进行了一些改进,以便独立调整列的大小

    print make_table( [      ['Name', 'Favorite Food', 'Favorite Subject'],
                             ['Joe', 'Hamburgrs', 'I like things with really long names'],
                             ['Jill', 'Salads', 'American Idol'],
                             ['Sally', 'Tofu', 'Math']])

    ===== ============= ==================================== 
    Name  Favorite Food Favorite Subject                     
    ===== ============= ==================================== 
    Joe   Hamburgrs     I like things with really long names 
    ----- ------------- ------------------------------------ 
    Jill  Salads        American Idol                        
    ----- ------------- ------------------------------------ 
    Sally Tofu          Math                                 
    ===== ============= ==================================== 

这是代码

def make_table(grid):
    max_cols = [max(out) for out in map(list, zip(*[[len(item) for item in row] for row in grid]))]
    rst = table_div(max_cols, 1)

    for i, row in enumerate(grid):
        header_flag = False
        if i == 0 or i == len(grid)-1: header_flag = True
        rst += normalize_row(row,max_cols)
        rst += table_div(max_cols, header_flag )
    return rst

def table_div(max_cols, header_flag=1):
    out = ""
    if header_flag == 1:
        style = "="
    else:
        style = "-"

    for max_col in max_cols:
        out += max_col * style + " "

    out += "\n"
    return out


def normalize_row(row, max_cols):
    r = ""
    for i, max_col in enumerate(max_cols):
        r += row[i] + (max_col  - len(row[i]) + 1) * " "

    return r + "\n"
于 2013-06-20T01:14:53.573 回答
1

您可以选择从 Python 转储到 CSV,然后使用 RST 的 csv-table 功能,如http://docutils.sourceforge.net/docs/ref/rst/directives.html#csv-table 它有:文件:指令简单地包含一个带有数据的 csv 文件。

于 2017-08-25T15:55:42.603 回答
0

这是@cieplak 的代码,添加了对字符串和多行支持的转换。也许它会对某人有用。

def make_table(grid):
    cell_width = 2 + max(reduce(lambda x,y: x+y, [[max(map(len, str(item).split('\n'))) 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:
        split_row = [str(cell).split('\n') for cell in row]
        lines_remaining = 1

        while lines_remaining>0:
            normalized_cells = []
            lines_remaining = 0
            for cell in split_row:
                lines_remaining += len(cell)

                if len(cell) > 0:
                    normalized_cell = normalize_cell(str(cell.pop(0)), cell_width - 1)
                else:
                    normalized_cell = normalize_cell('', cell_width - 1)

                normalized_cells.append(normalized_cell)

            rst = rst + '| ' + '| '.join(normalized_cells) + '|\n'

        rst = rst + table_div(num_cols, cell_width, header_flag)
        header_flag = 0
    return rst
于 2014-03-04T02:08:23.657 回答