public
Last active

Loading tabular data in Python

  • Download Gist
tabularize.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
def normalize_line(line):
return [piece.strip() for piece in line.split("|")[1:-1]]
 
def is_valid_line(line):
return "|" in line
 
def load(text):
lines = map(normalize_line,
filter(is_valid_line,
text.strip().splitlines()))
keys = lines.pop(0)
return [dict(zip(keys, line)) for line in lines]
 
 
print load("""
-------------------------------------------
| username | password | email |
-------------------------------------------
| edi | 123456 | |
| budu | 123456 | edi@edi.com |
| budu | 123456 | budu@budu.com |
| budu | 123456 | budu@budu.com |
| budu | 123456 | budu@budu.com |
-------------------------------------------
""")

Example use case for testing

def test_foo():
    """
    ---------------------
    | n1  | n2 | result |
    ---------------------
    | 1     | 2   | 3   |
    | 4     | 5   | 9   |
    | 3     | 4   | 7   |
    ---------------------
    """
    for row in load(test_foo.__doc__):
        assert int(row["n1"]) + int(row["n2"]) == int(row["result"])

test_foo()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.