繁体   English   中英

阅读新行的特定部分

[英]Reading specific sections of new lines

我正在尝试将文件中的多行保存到数组中。 我只希望该行的几部分,例如以下几行:

SAM_2216_geotag.JPG -81.5285781 41.0382292  418.13  279.04  -0.01   6.96
SAM_2217_geotag.JPG -81.5290933 41.0382309  418.94  279.34  -1.08   6.03
SAM_2218_geotag.JPG -81.5296101 41.0382294  419.31  287.49  -0.01   4.79

我想将所有第一组数字保存在自己的数组中,并保存第二组数字。

Array1= [-81.5285781, -81.5290933, -81.5296101]
Array2= [41.03822292, 41.0382309, 41.0382294]

到目前为止,我能够将每个新行保存到一个数组中,但是我很难摆脱不需要的数据。 这是我当前数组的一个元素:

SAM_2216_geotag.JPG\t-81.5285781\t41.0382292\t418.13\t279.04\t-0.01\t6.96\n'

如果有人可以帮助我获得阵列,那我将是一个很大的帮助。

您需要拆分数据,以便可以使用各个位。 尝试类似

columns = line.split()

关于string.split的文档

然后,您可以根据需要将它们放入数组中。 例如(使用循环):

array1 = []
array2 = []
for line in lines:
    columns = line.split()
    array1.append(columns[1])
    array2.append(columns[2])

这是使用re.search( https://docs.python.org/2/library/re.html#re.search ),拆分( https://docs.python.org/2/library/stdtypes )的一种方法。 html#str.split ),Zip( https://docs.python.org/2/library/functions.html#zip )和地图( https://docs.python.org/2/library/functions.html#地图

import re
out=[]

#Sample lines, you can just get these from file
line1 = "SAM_2216_geotag.JPG -81.5285781 41.0382292  418.13  279.04  -0.01   6.96"
line2 ="SAM_2217_geotag.JPG -81.5290933 41.0382309  418.94  279.34  -1.08   6.03"
line3 = "SAM_2218_geotag.JPG -81.5296101 41.0382294  419.31  287.49  -0.01   4.79"


#Create an array that has only the values you need. 
#You can replace the for below by using 'with open(file) as fH: and for line in fH'
for line in (line1, line2, line3):
    #line1 output: ['-81.5285781', '41.0382292', '418.13', '279.04', '-0.01', '6.96']
    out.append([x.strip() for x in line.split() if re.search('^[\d.-]+$', x.strip())])
#zip all the lists of out into list of tuples and then convert them to list of lists
#Please note that if your array lengths are uneven, you will get the shortest length output
print map (list, zip(*out))

输出:

[['-81.5285781', '-81.5290933', '-81.5296101'], 
 ['41.0382292', '41.0382309', '41.0382294'], 
 ['418.13', '418.94', '419.31'], 
 ['279.04', '279.34', '287.49'], 
 ['-0.01', '-1.08', '-0.01'], 
 ['6.96', '6.03', '4.79']
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM