anon
anon

Reputation: 11

How can I test a table written in Markdown with Python? (using Jupyter Notebook)

Say I got a table in a Markdown cell in Jupyter Notebook:

| Attr1 | Attr2 |
| :---: | :---: |
| Val11 | Val21 |
| Val12 | Val22 |

and now I want to test (in Python), whether the values in this table are correct. That is, if Attr1 = x, Attr2 = y, Val11 = x1, Val21 = y1, Val12 = x2, Val22 = y2. Is there any way around having to type the table into a string in python and then splitting the string up into the relevant words and then going through the list? Thanks in advance.

Upvotes: 1

Views: 407

Answers (1)

Tranbi
Tranbi

Reputation: 12721

It's a bit convoluted but you could use StringIO with pandas read_csv. Basically changing your markup table to a csv and loading it into a dataframe. That way you'd be able to perform all kinds of operations on your dataframe:

from io import StringIO
import pandas as pd

md_table_str = """| Attr1 | Attr2 |
| :---: | :---: |
| Val11 | Val21 |
| Val12 | Val22 |"""

table_csv = ""
for line in md_table_str.split('\n'):
    table_csv += line.strip('|') + '\n'

df = pd.read_csv(StringIO(table_csv), sep=' | ', engine="python")
print(df.drop(0)) # deleting first row (:---:)

Output:

   Attr1  |  Attr2
1  Val11  |  Val21
2  Val12  |  Val22

You can among other things access cell values:

print(df.at[1, 'Attr1'])

Upvotes: 1

Related Questions