2014-04-10 3 views
0

파일을 읽으려고하는데 파일에 여러 가지 종류의 데이터가 있습니다. 파일 형식의 예가 아래에 나와 있습니다.파이썬에서 파일을 읽는 데 도움이 필요합니다.

[CIRCUIT1] 
CIRCUITNAME=CIRCUIT1 
00.12 12/20 2.3 23.6 
00.12 12/20 2.3 23.6 
00.42 12/20 2.2 23.3 
00.42 12/20 2.2 23.3 

[CIRCUIT2] 
CIRCUITNAME=CIRCUIT2 
00.12 12/20 2.2 26.7 
00.12 12/20 2.2 26.7 
00.42 12/20 2.2 26.5 
00.42 12/20 2.2 26.5 
00.42 12/20 2.2 26.5 

[AMBIENT] 
00.42 12/20 8.6 
01.42 12/20 8.6 
02.42 12/20 8.6 
03.42 12/20 8.7 
04.42 12/20 8.8 
05.42 12/20 8.6 
06.42 12/20 8.7 

이제 circuit1의 3 번째 및 4 번째 열만 반환하는 함수를 정의했습니다. 하지만 날짜 및 시간 형식이 반환되어야하며 나중에 정의됩니다. 하지만 나는 범위 오류에서 색인을 얻고있다. 당신이 [AMBIENT]을 포함하는 행을 감지 한 후 추가 3. 당신의 읽기 상태를 변경하는 동안

def load_ci(filepath): 
    fileObj=open(filepath, 'r') 
    time_1=[],time_2=[],t=0,ti=0,loadCurrent_1=[],surfaceTemp_1=[],loadCurrent_2=[],surfaceTemp_2=[],ambient=[] 
    read=0 
    for line in fileObj: 
    if not line.strip(): 
     continue  
    if read==1: 
     if '[AMBIENT]' in line: 
      read=3 
      continue 
     elif 'CIRCUITNAME=CIRCUIT2' in line: read=2 
     else: 
      if line!='\n' and '[CIRCUIT2]' not in line: 
       point=line.split(' ') 
       t=(float(point[0])) 
       ti=int(t)*3600+(t-int(t))*60*100 
       time_1.append(ti) 
       loadCurrent_1.append(float(point[2])) 
       surfaceTemp_1.append(float(point[3])) 
    if read==2: 
     if '[AMBIENT]' in line: 
      read=3 
      continue 
     elif 'CIRCUITNAME=CIRCUIT2' in line: read=2 
     else: 
      if line!='\n' and '[CIRCUIT2]' not in line: 
       point=line.split(' ') 
       t=(float(point[0])) 
       ti=int(t)*3600+(t-int(t))*60*100 
       time_2.append(ti) 
       loadCurrent_2.append(float(point[2])) 
       surfaceTemp_2.append(float(point[3])) 
    if read==3: 
     if line!='\n': 
      point=line.split(' ') 
      ambient.append(float(point[2])) 
    if 'CIRCUITNAME=CIRCUIT1' in line: read=1 
return np.array(loadCurrent_1),np.array(surfaceTemp_1),np.array(loadCurrent_2),np.array(surfaceTemp_2),np.array(ambient),np.array(time_1),np.array(time_2) 

답변

0

, 당신은 계속, 다음 라인으로 향상시키는 데 필요한 문 2 점 = 3에서 읽기 후 당신이

또한 [AMBIENT] 확인 코드는 [CIRCUIT2]에서

if line != '\n' and line != '[CIRCUIT2]': 

012,351,641 확인 코드를 변경 당신은 빈 줄을 무시하려면
if line != '\n' and '[CIRCUIT2]' not in line: 

, 당신처럼 루프의 시작 부분에 체크를 추가 할 수는 :

if not line.strip(): 
    continue 

나는 주변에서 회로를 분석 탈출 할 수있는 문제의 코드를 재 작업했습니다 데이터, 상태 관리를 단순화합니다. 나는 파일 객체를 돌아 다니며 반복 상태를 이용하여 주어진 지점에서 파일의 위치를 ​​추적합니다. 파일의 섹션은 '[...]'로 시작하고 빈 줄로 끝나기 때문에이를 활용할 수 있습니다. 편의를 위해 모든 회로 데이터를 사전에 그룹화하지만 원하는 경우 완전한 원형 클래스로 롤아웃 할 수 있습니다.

import numpy as np 


def parseCircuit(it, header): 
    loadCurrent, surfaceTemp, time = [], [], [] 
    for line in it: 
     line = line.strip() 
     if not line: 
      break 
     elif line.startswith('CIRCUITNAME='): 
      name = line[12:] 
     else: 
      point=line.split(' ') 
      h, m = map(int, point[0].split('.')) 
      time.append(h * 3600 + m * 60) 
      loadCurrent.append(float(point[2])) 
      surfaceTemp.append(float(point[3])) 
    return {'name': name, 
      'surfaceTemp': np.array(surfaceTemp), 
      'loadCurrent': np.array(loadCurrent), 
      'time': np.array(time)} 


def parseAmbient(it, header): 
    ambient = [] 
    for line in it: 
     line = line.strip() 
     if not line: 
      break 
     point=line.split(' ') 
     ambient.append(float(point[2])) 
    return np.array(ambient) 


def load_ci(filepath): 
    fileObj=open(filepath, 'r') 
    circuits = {} 
    ambient = None 
    for line in fileObj: 
     line = line.strip()     # remove \n from end of line 
     if not line:       # skip empty lines 
      continue 
     if line.startswith('[CIRCUIT'): 
      circuit = parseCircuit(fileObj, line) 
      circuits[circuit['name']] = circuit 
     elif line.startswith('[AMBIENT'): 
      ambient = parseAmbient(fileObj, line) 
    return circuits, ambient 


print load_ci('test.ci') 

출력

({'CIRCUIT2': {'loadCurrent': array([ 2.2, 2.2, 2.2, 2.2, 2.2]), 'surfaceTemp': array([ 26.7, 26.7, 26.5, 26.5, 26.5]), 'name': 'CIRCUIT2', 'time': array([ 720, 720, 2520, 2520, 2520])}, 'CIRCUIT1': {'loadCurrent': array([ 2.3, 2.3, 2.2, 2.2]), 'surfaceTemp': array([ 23.6, 23.6, 23.3, 23.3]), 'name': 'CIRCUIT1', 'time': array([ 720, 720, 2520, 2520])}}, array([ 8.6, 8.6, 8.6, 8.7, 8.8, 8.6, 8.7])) 
+0

덕분 mtadd. 그것은 정말 잘 작동합니다. 이제는 시간 형식을 모아 두 번째 형식으로 배열에 저장하고 싶습니다. 시간을 초로 변환하는 데 필요한 변환 유형은 무엇입니까? –

관련 문제