对于 Python 初学者来说,我有一个艰巨的任务,我需要从用 LaTex 编写的源文件中导入一个表。我在想我将使用表的名称作为标识符,然后逐行写入一个数组,从表的开头到结尾。做这项工作的“自然”方式是什么?
问问题
1675 次
2 回答
6
astropy包有一个 LaTeX 表格阅读器。
from astropy.table import Table
tab = Table.read('file.tex')
reader 函数应该自动识别格式并读取文件中的第一个表。(如果您想要稍后的表格,请将相关部分剪切并粘贴到新文件中)。不过,读者有一些限制。最重要的是,每一行数据都必须在一行上(问题中表格的链接已经失效,所以我看不出这是否有问题),并且不能有\multicolumn
or之类的命令\multirow
。
查看 astropy 中的 Latex 阅读文档以获取更多选项:https ://astropy.readthedocs.org/en/latest/api/astropy.io.ascii.Latex.html#astropy.io.ascii.Latex
于 2016-02-10T11:39:21.727 回答
0
我个人会在表格的开头和结尾添加一个乳胶注释,以表示您感兴趣的行的范围。
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 文件中获取表格。一个明显的问题是它读取文件两次并且绝对可以优化。
于 2015-12-11T14:48:53.457 回答