2014-04-12 5 views
0

본질적으로 다른 소프트웨어 용으로 변환하기 위해 유전자형 데이터를 구문 분석하려고합니다. 질문이 너무 구체적이지만 미안하지만 의견이나 제안을 매우 높이 평가합니다.요소를 대체하여 데이터 집합을 다시 포맷하십시오.

ID, exp, control 
1, aa, bb 
2, ab, aa 
3, ab, - 

내가이 같은 변화 것 :

  1. 반복 각 열하지만 첫 번째.
  2. 대체 'aa', 'bb'는 첫번째는 'a'로 대체 될 것이다 'ab''a', 'b', 같은 'b'로 대체 될 중복.

    ID exp exp control control 
        1 a a b b 
        2 a b a a 
        3 a b 0 0 
    

    예를 들어

은 어떻게 든 첫 번째 목표를 달성하기 위해 관리,하지만 난 인쇄물이 약간 이상한 발견하고 교체의 모든 실행되지 않은 :

ID exp exp  control 
    control 

1 aa  aa bb 
    bb 

2 ab  ab aa 
    aa 

3 ab  ab - 
    -  

여기 내 코드는 다음과 같습니다.

#!/usr/bin/env python 

inputfile = open("test.txt", 'r') 
outputfile = open("solomon.txt", 'w') 
matchlines = inputfile.readlines() 

for line in matchlines: 
     line_parts = line.strip() #strip the end space 
     line_parts = line.split(',') #split the line 
     output_parts = [] 
     for part in line_parts[1:]: #start from 2nd element, so 1st column not duplicate 

      if part == 'aa': 
       part = part.replace('aa', 'a') 
      elif part == 'bb': 
       part = part.replace('bb', 'b') 
      elif part == '-': 
       part = part.replace('-', '0') 
      elif part == 'ab': 
       '''the original one will be replaced with 'a' the duplciatd on will be replaced as 'b' ''' 
      else: 
       print 'Nothing is matched' 
      output_part = part + '\t' + part #duplicate each element (1st goal)    
      output_parts.append(output_part) #populate the line  
      line = '\t'.join(output_parts) #join elements in the line with a tab     
     outputfile.write(line_parts[0] + line + "\n") 

inputfile.close() 
outputfile.close() 

답변

2

나는 separat e 기능을 제공하므로 다른 요소와 별도로 개발하고 테스트하기가 더 쉽습니다.

def process_line(line_parts): 
    out = line_parts[:1] 
    for part in line_parts[1:]: 
     if part == "-": 
      out.extend('00') 
     else: 
      out.extend(part) 
    return out 

.

>>> process_line(['1', 'aa', '-']) 
['1', 'a', 'a', '0', '0'] 

>>> process_line(['1', 'ab', 'bb']) 
['1', 'a', 'b', 'b', 'b'] 

당신은 쉽게 str.join와 공백으로 구분 된 문자열을 만들 수 있습니다

>>> " ".join(['1', 'a', 'a', '0', '0']) 
'1 a a 0 0' 
+0

덕분에 많이, 당신은 조금 설명 할 수 내 대체 작동하지 않는 이유? – user2489612

+0

알기가 어렵습니다. 질문을 검토하여 실행중인 들여 쓰기와 일치하는지 확인하십시오. – jonrsharpe

관련 문제