簡體   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