在Python中从文件读取格式化的数组

时间:2019-05-09 06:47:11

标签: python io

我有一个文件,其中包含一些字符串,然后包含两个格式化的数组。看起来像这样

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]

我事先不知道数组的 size 。我唯一知道的是数组[]定界符。什么是读取数组的一种优雅方法。

我是python的新手。

2 个答案:

答案 0 :(得分:2)

使用正则表达式。 re.findall

例如:

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))

输出:

[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]

答案 1 :(得分:0)

我不会称它为优雅,但是它可以工作

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(',')])