Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 阅读新行的特定部分_Python_Arrays_File Io - Fatal编程技术网

Python 阅读新行的特定部分

Python 阅读新行的特定部分,python,arrays,file-io,Python,Arrays,File Io,我正在尝试将文件中的多行保存到数组中。我只想要几段线,这里有几段线,例如: 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

我正在尝试将文件中的多行保存到数组中。我只想要几段线,这里有几段线,例如:

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()
然后,您可以根据需要将它们放入数组中。例如,使用循环:

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

这里有一种方法可以使用re.search、split、Zip和map

输出:

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']
]