Reading a LaTex table into an array in Python

I have a tricky task for those new to Python, I need to import a table from a source file that is written in LaTex. I thought I would use the table name as an identifier and then write line by line into the array from the beginning of the table to the end of it. What is the "natural" way to get this job done?

+3


source to share


2 answers


astropy package contains a LaTeX table reader.

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

      



The read 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). However, the reader has some limitations. Most importantly, each row of data must be on one line (the table reference in the questions is dead, so I can't see if this is the problem) and there cannot be commands like \multicolumn

or \multirow

.

Check out docs for reading latex in astropia for more options: https://astropy.readthedocs.org/en/latest/api/astropy.io.ascii.Latex.html#astropy.io.ascii.Latex

+3


source


I personally would put a latex comment at the beginning and end of the table to indicate the range of lines you are interested in.

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 above code was executed without testing, but should get the table from your .tex file. One obvious problem is that it reads the file twice and can definitely be optimized.

0


source







All Articles