在Python中将LaTex表格读入数组

5 投票
2 回答
2761 浏览
提问于 2025-04-17 16:16

我有一个对Python初学者来说有点难的任务,我需要从一个用LaTex写的源文件中导入一个表格。我想用表格的名字作为标识符,然后一行一行地把内容写入一个数组,从表格的开头到结尾。请问这个工作有什么“自然”的方法吗?

2 个回答

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文件中提取出表格。不过,有一个明显的问题就是它读取文件的次数是两次,这样的做法肯定可以优化一下。

6

astropy包有一个可以读取LaTeX表格的功能。

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

这个读取功能会自动识别文件的格式,并读取文件中的第一个表格。如果你想读取后面的表格,可以把相关部分剪切粘贴到一个新文件里。不过,这个读取功能有一些限制。最重要的是,每一行的数据必须在同一行上(因为问题中的表格链接已经失效,所以我无法确认这是否是个问题),而且不能有像\multicolumn\multirow这样的命令。

想了解更多关于在astropy中读取LaTeX的选项,可以查看文档:https://astropy.readthedocs.org/en/latest/api/astropy.io.ascii.Latex.html#astropy.io.ascii.Latex

撰写回答