0

程序以下列方式将列表写入 .txt 文件:

[ 3.  6.  3.  1.  1.  1.  0.  1.  2.  2.  9.  2.  5.  2.  2.  1.  0.  0.
  4.  6.  1.  1.  1.  0.  5.  2.  0.  0.  0.  0.  0.  0.  0.  0.]
[  4.   9.   8.   7.   2.   4.   1.   7.   5.   3.   7.   2.   6.   0.   9.
  5.   6.  10.   6.   2.   1.   5.   0.]
[  3.   5.   9.   1.   1.   1.   0.   1.   1.   4.   8.   5.   5.   3.   3.
   7.   6.  12.   9.   2.   1.   0.   0.   4.   6.   1.   1.   1.   0.   5.
   0.   0.   0.   0.   0.   0.   0.   0.   0.]

即,列表不在一行上。我想为这些列表中的每一个创建一个直方图,在确保导入整个列表(而不是单行)之后,如何在列表中导入这些整数值?我努力了:

data = [line.strip() for line in open('n.txt', 'r')]

但是当调用 data[0] 时,它只会产生顶行。有什么建议么?

4

3 回答 3

0

粗略,但应该加入行而不将所有数据同时加载到内存中。

a_lines = list()
str_line = ''

for line in [l.rstrip() for l in open('data.txt')]:
    str_line += line
    if str_line[-1] == ']':
        a_lines.append(str_line)
        str_line = ''

my_data = '\n'.join(a_lines)

在这里regex

import re

p = re.compile(r'([^\]])\n', re.MULTILINE)
my_data = ''

with open('data.txt') as my_file:
    my_data = p.sub(r'\1', my_file.read())

两个代码示例都将数据保留在一个字符串元素中,my_data

于 2013-08-22T00:05:16.413 回答
0

If you're in control of the writing to the file, there are easier formats to write this data. But if you're stuck with this, here's one way to load it:

import ast

with open('test.txt', 'r') as f:
    data = []
    curList = []
    for line in f:
        line = line.replace('[', ' [ ').replace(']', ' ] ')
        items = line.split()
        for item in items:
            if item == "[":
                curList = []
            elif item == "]":
                data.append(curList)
            else:
                curList.append(ast.literal_eval(item))

print data

OUTPUT:

[[3.0, 6.0, 3.0, 1.0, 1.0, 1.0, 0.0, 1.0, 2.0, 2.0, 9.0, 2.0, 5.0, 2.0, 2.0, 1.0, 0.0, 0.0, 4.0, 6.0, 1.0, 1.0, 1.0, 0.0, 5.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 
 [4.0, 9.0, 8.0, 7.0, 2.0, 4.0, 1.0, 7.0, 5.0, 3.0, 7.0, 2.0, 6.0, 0.0, 9.0, 5.0, 6.0, 10.0, 6.0, 2.0, 1.0, 5.0, 0.0], 
 [3.0, 5.0, 9.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 4.0, 8.0, 5.0, 5.0, 3.0, 3.0, 7.0, 6.0, 12.0, 9.0, 2.0, 1.0, 0.0, 0.0, 4.0, 6.0, 1.0, 1.0, 1.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
于 2013-08-21T23:48:07.260 回答
0

基于以下事实的不同方法:新列表由 指示[

data = []
with open("n.txt") as fh:
    for line in fh:
        line = line.replace('.', '').replace(']', '')
        line = line.split()
        if line[0] == '[':
            data.append(map(int, line[1:]))
        else:
            data[-1].extend(map(int, line))

点被删除,以便int以后工作。它依赖于每个之后至少有一个空格[(在您的简短示例中是正确的),但如果这不是真的,您可以轻松适应,例如使用 Brionius 答案中的替换。

于 2013-08-22T02:34:33.563 回答