5

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?

2
  • 1
    What does the table look like? Please give an example... Commented Feb 18, 2013 at 16:29
  • Hi, here's how the table looks like - dpaste.com/1022705 Commented Mar 14, 2013 at 13:34

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.