2017-02-19 65 views
1

我试图用这个代码解析一个CSV文件,但无法找到解决这个错误我的方式:IndexError:列表索引超出范围CSV解析器的

“文件‘(文件位置)’,管道438,在parser_42

位置= TMP2 [1]

IndexError:列表索引超出范围”

我的CSV文件的结构如下所示:

突变系数在sco重新

Q41V -0.19 0.05

Q41L -0.08 0.26

Q41T -0.21 0.43

I23V -0.02 0.45

I61V 0.01 1.12

我想利用突变体并且例如分开'Q''41'和'V'。 然后,我想要创建位置和wt列表并按数字顺序放置它们。

目标是字符串“序列”写入新的csv文件

很明显,我在Python和数据处理初学者。我想我只是在俯视一些愚蠢的东西......任何人都可以把我引向正确的方向吗?

def parser_42(csv_in, fasta_in, *args): 

    with open(csv_in, 'r') as tsv_in: 
     tsv_in = csv.reader(tsv_in, delimiter='\t') 
     next(tsv_in) # data starts on line 7 
     next(tsv_in) 
     next(tsv_in) 
     next(tsv_in) 
     next(tsv_in) 
     next(tsv_in) 

     for row in tsv_in: 
      tmp = row[0].split(',') 
      tmp2 = re.split('(\d+)', tmp[0]) 
      wt = tmp2[0] 
      position = tmp2[1] 
      substitution = tmp[2] 

      seq = "" 
      current_positions = [] 


      if position not in current_positions: 
       current_positions += [position] 
       print(current_positions) 
       seq += wt 
      else: 
       continue 

     print(seq) 
+0

它看起来像你的CSV只有每行和youre设法存取权限第二个值与'TMP2一个值[1]' – Craicerjack

+0

你可能有一个空行的地方,可能是在文件的结尾。 – TigerhawkT3

+0

分离之后,您可以在继续访问不存在的索引之前检查结果的长度。 –

回答

1

的人谁可能有兴趣,这是我如何解决我的问题......如果任何人有关于如何使这一点更简洁的任何建议,意见,将不胜感激。我知道这可能看起来像是一个迂回的方式来解决一个小问题,但我在这个过程中学到了相当数量的东西,所以我并不过分担心:)。我基本上用正则表达式替换了.split(),这似乎更干净一些。

def parser_42(csv_in, fasta_in, *args): 
    dataset = pd.DataFrame(columns=get_column_names()) 
    with open(csv_in) as tsv_in: 
     tsv_in = csv.reader(tsv_in, delimiter='\t') 
     next(tsv_in) #data starts on row 7 
     next(tsv_in) 
     next(tsv_in) 
     next(tsv_in) 
     next(tsv_in) 
     next(tsv_in) 
     save_path = '(directory path)' 
     complete_fasta_filename = os.path.join(save_path, 'dataset_42_seq.fasta.txt') 
     output_fasta_file = open(complete_fasta_filename, 'w') 

     seq = '' 
     current_positions = [] 

     for row in tsv_in: 

     # regular expressions to split numbers and characters in single cell 
      regepx_match = re.match(r'([A-Z])([0-9]+)([A-Z,*])', row[0], re.M | re.I) 
      wt = regepx_match.group(1) 
      position = int(regepx_match.group(2)) 
      substitution = regepx_match.group(3) 

      if position not in current_positions: 
       current_positions += [position] 
       seq += wt 
      else: 
       continue 
     seq = list(seq) 

    # this zips seq and current_positions and sorts seq 
     sorted_y_idx_list = sorted(range(len(current_positions)), key=lambda x: current_positions[x]) 
     Xs = [seq[i] for i in sorted_y_idx_list] 

     seq1 = '>dataset_42 fasta\n' 
     seq1 = seq1 + ''.join(Xs) # join to string 


     output_fasta_file.write(seq1) 
     output_fasta_file.close() 
相关问题