Reputation: 2442
I have a difficult mission for a beginner in Python, I need to import a table from a source file which is written in LaTex. I was thinking I will use the name of the table as identifier, and then write line by line into an array, from the beginning of the table to its end. What is the "natural" way to do this job?
Upvotes: 5
Views: 3150
Reputation: 698
The astropy package has a LaTeX table reader.
from astropy.table import Table
tab = Table.read('file.tex')
The reader function should automatically recognize the format and read the first table in the file. (Cut and paste the relevant section into a new file if you want a later table).
The reader has some limitations, though. Most importantly, every row of data has to be on a single line (The link to the table in the questions is dead, so I cannot see if this is a problem) and there cannot be commands like \multicolumn
or \multirow
.
Check the docs for Latex reading in astropy for more options: https://astropy.readthedocs.org/en/latest/api/astropy.io.ascii.Latex.html#astropy.io.ascii.Latex
Upvotes: 6
Reputation: 1524
I would personally put in a latex comment at the beginning and end of the table to denote the range of lines that interest you.
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)]
The code above was done without testing but should get you the table from your .tex file. One obvious issue with it though is that it reads the file twice and can definitely be optimised.
Upvotes: 0