1

I have a file which contains some strings and then two formatted arrays. It looks something like this

megabuck
Hello world

[58, 50, 42, 34, 26, 18, 10, 2,
      61, 53, 45, 37, 29, 21, 13, 5,
      63, 55, 47, 39, 31, 23, 15, 7]

[57, 49, 41, 33, 25, 17, 9,
        1, 58, 50, 42, 34, 26, 18,
        14, 6, 61, 53, 45, 37, 29,
        21, 13, 5, 28, 20, 12, 4]

I don't know the size of the arrays beforehand. Only thing I know is the delimiter for the array which is []. What can be an elegant way to read the arrays.

I am a newbie in python.

1
  • The best way would be to load them in as a python object and use list.len() Commented May 9, 2019 at 6:52

2 Answers 2

3

Using Regex. re.findall

Ex:

import re
import ast

with open(filename) as infile:
    data = infile.read()

for i in re.findall(r"(\[.*?\])", data, flags=re.S):
    print(ast.literal_eval(i))

Output:

[58, 50, 42, 34, 26, 18, 10, 2, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7]
[57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4]
Sign up to request clarification or add additional context in comments.

Comments

0

I wouldn't call it elegant but it works

ars = """
megabuck
Hello world

[58, 50, 42, 34, 26, 18, 10, 2,
    61, 53, 45, 37, 29, 21, 13, 5,
    63, 55, 47, 39, 31, 23, 15, 7]

[57, 49, 41, 33, 25, 17, 9,
        1, 58, 50, 42, 34, 26, 18,
        14, 6, 61, 53, 45, 37, 29,
        21, 13, 5, 28, 20, 12, 4]
"""
arrays = [] 
for a in ars.split("["):
    if ']' in a:
        arrays.append([i.strip() for i in a.replace("]",'').split(',')])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.