2011-08-02 79 views
0

我有GPRMC字符串,它由12個逗號分隔的值組成。當我運行我的代碼時,它實際上會分割逗號,但它會在新行中以逗號分隔值打印每個字符 - 而不是將所有字符分組在一起。Python用CSV解析GPRMC字符串

例如:

>>> gprmc = "$GPRMC,1244.0,A,3111.334505,N,90729.3111898,W,1.2,,020811,,,A*55" 
>>> gprmcReader = csv.reader(gprmc) 
>>> for val in gprmcReader: 
    print val 


['$'] 
['G'] 
['P'] 
['R'] 
['M'] 
['C'] 
['', ''] 
['1'] 
['2'] 
['4'] 
['4'] 
['.'] 
['0'] 
['', ''] 
['A'] 
['', ''] 
['3'] 
['1'] 
['1'] 
['1'] 
['.'] 
['3'] 
['3'] 
['4'] 
['5'] 
['0'] 
['5'] 
['', ''] 

回答

0

試試這個:

import csv 
reader = csv.reader(open(filename, 'r')) 

for row in reader: 
    if row and row[0].strip() == '$GPRMC': 
     for val in row: 
      print val 
     print "_____________________" 

要檢查我的代碼創建文件,其中包含以下列文本一行:

$GPRMC,135005.0,A,3526.351705,N,90729.337898,W,1.2,,020811,,,A*55 

執行我的代碼打印我:

$GPRMC 
135005.0 
A 
3526.351705 
N 
90729.337898 
W 
1.2 

020811 


A*55 
+0

我不在乎剝離GPRMC。我只是想在每個逗號之間的所有字符被分組在一起 – danes

+0

你是什麼意思的分組可以請你更新你的問題,告訴我們你真正想要什麼,因爲我的代碼給了我你在問題中提到的輸出 –

+0

我得到我運行此代碼時出現索引異常。 – danes