拆分字符串然后按字符编号拆分

时间:2015-01-16 10:20:09

标签: python string split character

我有一个包含许多行的信息文件,一些行上有一组数据对。我想提取成对的深度和温度。对在字符64之后开始,每对占用17个字符的空间。

我目前正在做的是切断字符64处的字符串(63用python计数),然后每隔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

1 个答案:

答案 0 :(得分: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