在白色上拆分字符串 space
Split string on white space
我试图读入这个格式奇怪的文本文件,但我不知道如何告诉 python 每行都以分隔符开头。
文本文件中的一行如下所示:
3.146 -1.339 .358 29.214
文件使用5个空格作为分隔符。如何将每一行读入包含 4 个项目的列表?
您可以使用以下方法将每一行读入包含 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 ]
结合使用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])
这是您的分隔符:
delimiter=' '
然后您只需使用定界符拆分您的文本行
lineoftext.split(delimiter)
我试图读入这个格式奇怪的文本文件,但我不知道如何告诉 python 每行都以分隔符开头。
文本文件中的一行如下所示:
3.146 -1.339 .358 29.214
文件使用5个空格作为分隔符。如何将每一行读入包含 4 个项目的列表?
您可以使用以下方法将每一行读入包含 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 ]
结合使用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])
这是您的分隔符:
delimiter=' '
然后您只需使用定界符拆分您的文本行
lineoftext.split(delimiter)