2015-01-16 164 views
2

我有一個包含許多行的信息文件,一些行上有一組數據對。我想提取深度和溫度對。這些對在字符64之後開始,並且每一對佔據17個字符的空間。分割一個字符串,然後按字符分割

我現在正在做的是切斷字符64(63 python counting),然後分割字符串每17個字符。 如果這兩對之間有空白,這可以很好地工作,但是由於深度很大,所以有些對不需要。 下面是例子:

' 1.9901 954.01' 
' 1.43011675.01' 

臨時佔用前10個字符和深度下一7.因此,我願做這樣的方式,我可以單獨提取所有值的分割線是什麼然後將它們配對。

但是,我正在創建一個分割增加7或10的問題。我也不確定python將字符串轉換爲列表並保留字符長度時發生了什麼。

這是我工作的代碼:

import os, re 
import string 

with open('TE_feb_2014.pos','r') as file: 
    for line in file: 
    m = re.search('(TEMP01)', line) 
    if m: 
     values = string.split(line[63:]) 
     #print values 
     n = 17 
     [values[i:i+n] for i in range(0, len(values), n)] 
     print values 

下面是一個例子數據線(沒有上述問題):

00087501 297017Q990066614201402251006TE  42550TEMP01 18D 2.01 -1.2801 50.01 -1.1601 99.01 -0.5901 148.01 -0.8001 197.01 -1.1001 245.01 -1.7501 295.01 -1.7701 301.01 -1.7801 343.01 -1.7301 392.01 -1.6701 441.01 -1.5901 489.01 -1.4501 538.01 -1.1401 587.01 -0.7201 635.01 -0.3201 684.01 0.3501 731.01 0.6201 733.01 0.6201 
+3

你能提供一個多行示例(並且最好至少有一行顯示出問題)嗎? –

回答

2

好像你想是這樣的,

>>> import re 
>>> s = "00087501 297017Q990066614201402251006TE  42550TEMP01 18D 2.01 -1.2801 50.01 -1.1601 99.01 -0.5901 148.01 -0.8001 197.01 -1.1001 245.01 -1.7501 295.01 -1.7701 301.01 -1.7801 343.01 -1.7301 392.01 -1.6701 441.01 -1.5901 489.01 -1.4501 538.01 -1.1401 587.01 -0.7201 635.01 -0.3201 684.01 0.3501 731.01 0.6201 733.01 0.6201" 
>>> m = re.sub(r'^.{64}', r'', s) # To remove the first 64 characters from the input string. 
>>> re.findall(r'.{1,17}', m)  # To find all the matches which has the maximum of 17 characters and a minimum of `1` character. 
[' 2.01 -1.2801 ', ' 50.01 -1.1601 ', ' 99.01 -0.5901 ', '148.01 -0.8001 ', '197.01 -1.1001 ', '245.01 -1.7501 ', '295.01 -1.7701 ', '301.01 -1.7801 ', '343.01 -1.7301 ', '392.01 -1.6701 ', '441.01 -1.5901 ', '489.01 -1.4501 ', '538.01 -1.1401 ', '587.01 -0.7201 ', '635.01 -0.3201 ', '684.01 0.3501 ', '731.01 0.6201 ', '733.01 0.6201'] 
>>> for i in re.findall(r'.{1,17}', m): 
     print(i) 


    2.01 -1.2801 
50.01 -1.1601 
99.01 -0.5901 
148.01 -0.8001 
197.01 -1.1001 
245.01 -1.7501 
295.01 -1.7701 
301.01 -1.7801 
343.01 -1.7301 
392.01 -1.6701 
441.01 -1.5901 
489.01 -1.4501 
538.01 -1.1401 
587.01 -0.7201 
635.01 -0.3201 
684.01 0.3501 
731.01 0.6201 
733.01 0.6201