Python 在空白处拆分字符串
我有一个奇怪的格式化文本文件,我正试图读入它,但我不知道如何告诉python每一行都以分隔符开头 文本文件中的一行如下所示:Python 在空白处拆分字符串,python,python-2.7,delimiter,Python,Python 2.7,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',
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 ]
您可以使用以下命令将每行读入包含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])
使用
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=''
然后使用分隔符拆分文本行
lineoftext.split(分隔符)
line.strip().split()
?line.strip().split()
?readlines()
将返回一个列表。您不能split()
a列表。您需要拆分列表中的每一行。为了可读性,不如lines=[line.strip().split()(用于f中的行)
Good point!在这种情况下,由于我们没有使用非平凡的lambda(Guido对此不屑一顾),我认为两者都或多或少具有相同的可读性(当然,map
不那么像Pythonic…)。如果我们想添加.strip()
,那么LC肯定是更好的选择.split()
应该在行中的所有空格上进行拆分,因此这里可能不需要strip
。readlines()
将返回一个列表。您不能split()
a列表。您需要拆分列表中的每一行。为了可读性,不如lines=[line.strip().split()(用于f中的行)
Good point!在这种情况下,由于我们没有使用非平凡的lambda(Guido对此不屑一顾),我认为两者都或多或少具有相同的可读性(当然,map
不那么像Pythonic…)。如果我们想添加.strip()
,那么LC肯定是更好的选择.split()
应该在行中的所有空格上拆分,因此这里可能不需要strip
。