在Python中将LaTex表格读入数组

5

对于 Python 的初学者来说,我有一个比较困难的任务:需要从 LaTeX 格式的源文件中导入一张表格。我的想法是使用表格名称作为标识符,然后逐行写入数组中,从表格头开始到表格尾结束。请问这个任务最自然的解决方式是什么?


1
表格长什么样?请举个例子... - Jan
嗨,这是表格的样子 - http://dpaste.com/1022705/ - Ohm
2个回答

6

Astropy 软件包 包含一个 LaTeX 表格读取器。

from astropy.table import Table
tab = Table.read('file.tex')

读取函数应该自动识别格式并读取文件中的第一个表格。(如果您想要较晚的表格,请将相关部分剪切并粘贴到新文件中)。然而,读取器有一些限制。最重要的是,每行数据必须在单独的一行上(由于问题中的表格链接已失效,因此我无法确定这是否是一个问题),而且不能有像 \multicolumn\multirow 这样的命令。
请查看Latex阅读astropy文档以获取更多选项:https://astropy.readthedocs.org/en/latest/api/astropy.io.ascii.Latex.html#astropy.io.ascii.Latex

0

我个人会在表格的开头和结尾处加入一个 LaTeX 注释,以表示你感兴趣的行范围。

import linecache
FILEPATH = 'file.tex'


def get_line_range():
    'returns the lines at which the table begins and ends'
    begin_table_line = None
    end_table_line = None
    with open(FILEPATH, "r") as file:
        array = []
        for line_number, line in enumerate(file):
            if 'latex comment denoting beginning of table' in line:
            begin_table_line = line_number

            if 'latex comment denoting end of table' in line:
            end_table_line = line_number

    return begin_table_line+1, end_table_line

def get_table():
    'gets the lines containing the table'
    start, end = get_line_range()
    return [linecache.getline(FILEPATH, line) for line in xrange(start, end)]

以上代码没有经过测试,但应该可以从你的 .tex 文件中获取表格。其中一个明显的问题是它会两次读取文件,肯定可以进行优化。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接