我有一个Python元组列表,我想输出到reStructuredText中的表。
docutils库为将reStructuredText转换为其他格式提供了强大的支持,但是我想直接从内存中的数据结构写入reStructuredText。
最佳答案
我不知道有任何库可以从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
===== ===== =========
关于python - 有什么方法可以将Python数据结构输出到reStructuredText,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11347505/