Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将Python数据结构输出到重构的DText有哪些方法_Python_Restructuredtext - Fatal编程技术网

将Python数据结构输出到重构的DText有哪些方法

将Python数据结构输出到重构的DText有哪些方法,python,restructuredtext,Python,Restructuredtext,我有一个Python元组列表,我想将其输出到StructuredText中的表中 docutils库非常支持将StructuredText转换为其他格式,但我想直接从内存中的数据结构写入StructuredText。我不知道有任何库可以从python数据结构输出RST,但是自己格式化它很容易。下面是将python元组列表格式化为RST表的示例: >>> data = [('hey', 'stuff', '3'), ('table', 'row', 'so

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


docutils库非常支持将StructuredText转换为其他格式,但我想直接从内存中的数据结构写入StructuredText。

我不知道有任何库可以从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      
===== ===== =========
>>数据=[('hey','stuff','3'),
(‘表’、‘行’、‘某物’),
('xy','z','abc')]
>>>numcolumns=len(数据[0])
>>>colsize=[max(len(r[i])表示数据中的r)表示范围中的i(numcolumns)]
>>>格式化程序=''.join('{:
以下是我用于快速和脏的重构文本表的代码:

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)) * ' ')

@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"

这里是@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
看看包裹。 它可以通过以下方式输出RST格式:

print tabulate(table, headers, tablefmt="rst")

您可以选择从Python转储到CSV中,然后使用RST的CSV表功能,如中所示 它有一个:file:指令,只包含一个包含数据的csv文件

print tabulate(table, headers, tablefmt="rst")