如何从python中的文本文件中只获取数字(没有空格)

时间:2016-07-08 15:52:41

标签: python list append text-files

您好我有这个文本文件:

1 2 3 4 5 6
1 1 1 1 1 1
-1 1 -1 -1 -1 1
2 3 5 6 1 6
10 0 0.5 1 0 0
0 30 5 3 0 0
0 0 0 0 0 5
80 90 6 5,4 8 5
65 58 2 9,7 1 1
83 60 4 7,2 4 7
40 80 10 7,5 7 10
52 72 6 2 3 8
94 96 7 3,6 5 6

我想在7个不同的列表中添加7个第一行(如果可能的话,使用for循环),如下所示:

a=[1 2 3 4 5 6]
b=[1 1 1 1 1 1]

等等其余的5.然后我希望将文件的剩余6行附加到带有for循环的列表列表中(这样如果我有剩余的6行以上,代码就会不改变)像这样:

mylol=[[80 90 6 5,4 8 5],[65 58 2 9,7 1 1],[83 60 4 7,2 4 7],[40 80 10 7,5 7 10],[52 72 6 2 3 8],[94 96 7 3,6 5 6]]

这样我就可以使用每个列表列表的每个数字,因为我想进行数学运算。我注意到在列表列表的末尾我尝试使我有一个如下所示的列表:

['']   

如果可能,我不想要它。

到目前为止我有这个代码,但我想要更像我要求的东西:

with open("c.txt") as file:
lines = []
for line in file:
    # The rstrip method gets rid of the "\n" at the end of each line
    lines.append(line.rstrip().split(","))
print lines

3 个答案:

答案 0 :(得分:0)

shlex是你的朋友https://docs.python.org/2/library/shlex.html

with open("c.txt") as file:
lines = []
for line in file:
 # The rstrip method gets rid of the "\n" at the end of each line
 lines.append(shlex.split(line))
print lines

shlex.split()会按您的意愿执行

答案 1 :(得分:0)

如果您真的希望列表看起来像这样:

a = [1, 2, 3, 4, 5, 6]

然后项目必须是数字(整数或浮点数)。

但是,您的输入文件包含一些如下所示的项目:

5,4

这既不是整数也不是浮点数。

因此,您必须将项目存储为字符串,这意味着您将看到引号:

a = ['80', '90', '6', '5,4', '8', '5']

或者,您必须找出处理5,4等项目的方法,以便将它们转换为数字。

编辑:

如果编辑文件以将逗号更改为句点,则可以使用以下代码:

with open("c.txt") as file:
lines = []
for line in file:
    current_line = []
    # The rstrip method gets rid of the "\n" at the end of each line
    for item in line.rstrip().split():
        if '.' in item:
            current_line.append(float(item))
        else:
            current_line.append(int(item))
    lines.append(current_line)
print lines

答案 2 :(得分:0)

final_list = []
with open("c.txt") as f:
    count = 0
    for line in f:
        line_list = [float(n) for n in line.rstrip().replace(',', '.').split(" ")]
        if count < 7:
            final_list.append(line_list)
        else:
            if count == 7:
                final_list.append([])
            final_list[7].append(line_list)
        count += 1

这将输出他们自己列表中的前7行,然后其余行将添加到列表中输出以下内容的列表中:

[[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [-1.0, 1.0, -1.0, -1.0, -1.0, 1.0], [2.0, 3.0, 5.0, 6.0, 1.0, 6.0], [10.0, 0.0, 0.5, 1.0, 0.0, 0.0], [0.0, 30.0, 5.0, 3.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 5.0], [[80.0, 90.0, 6.0, 54.0, 8.0, 5.0], [65.0, 58.0, 2.0, 97.0, 1.0, 1.0], [83.0, 60.0, 4.0, 72.0, 4.0, 7.0], [40.0, 80.0, 10.0, 75.0, 7.0, 10.0], [52.0, 72.0, 6.0, 2.0, 3.0, 8.0], [94.0, 96.0, 7.0, 36.0, 5.0, 6.0]]]

它解释了应该是小数的逗号,并将数字插入浮点数。