在白色空间的分裂串

时间:2015-11-14 18:20:53

标签: python python-2.7 delimiter

我有这个奇怪的格式化文本文件我试图读入,我不知道如何告诉python每行以分隔符开头。

文本文件中的一行如下所示:

     3.146    -1.339      .358    29.214

该文件使用5个空格作为分隔符。如何将每行读入包含4个项目的列表?

3 个答案:

答案 0 :(得分:3)

您可以使用以下内容将每行读入包含4个项目的列表中:

with open(filename, 'r') as f:

    # this will read in each row as:
    #
    #   ['3.146', '-1.339', '.358', '29.214']
    #
    # so `lines` will contain
    #
    #   [['3.146', '-1.339', '.358', '29.214'], ...]
    lines = map(str.split, f.readlines())

    # or alternatively, as @jez mentioned, it may be more readable to use
    lines = [ line.split() for line in lines ]

    # you'll then likely want to convert them to floats
    # 
    # this will give you:
    #
    #   [[3.146, -1.339, 0.358, 29.214], ...]
    data = [ map(float, split_line) for split_line in lines ]

答案 1 :(得分:1)

使用split结合strip删除多余的空格:

my_file_data = "     3.146    -1.339      .358    29.214"
data = my_file_data.strip().split('     ')
# do stuff with your data
print(data[0])

答案 2 :(得分:0)

这是你的分隔符:

delimiter=' '

然后,您只需使用分隔符

分割您的文本行

lineoftext.split(delimiter)