拆分和连接文件中的列

时间:2014-08-19 14:00:40

标签: python string join split

我有以下格式的文件

score   div del ins  sequence  begin  end      (left)   repeat       class/family   begin  end    (left)  ID
   35    5.1  8.2  0.0  chrI           2     62 (230156) + (CA)n        Simple_repeat       1     66    (0)   1  
   14   16.5  5.7  7.2  chrI         231    300 (229918) + (TACCCA)n    Simple_repeat       1     69    (0)   2  
   17    0.0  0.0  0.0  chrI        6737   6755 (223463) + (A)n         Simple_repeat       1     19    (0)   3  
   14    4.3  4.2  0.0  chrI        9229   9252 (220966) + (TATT)n      Simple_repeat       1     25    (0)   4  
   11    3.8  6.5  6.5  chrI       12864  12894 (217324) + GA-rich      Low_complexity      1     31    (0)   5  
  691   25.7  4.5  4.5  chrI       22230  22539 (207679) + TY           LTR/Copia        5702   6011  (525)   6  
   26   14.1  1.7  3.5  chrI       23706  23712 (206506) + (ATAA)n      Simple_repeat       1     25   (33)   7  
   28   14.6  0.0  0.0  chrI       23713  23758 (206460) + (A)n         Simple_repeat       1     46    (0)   8  
   26   14.1  1.7  3.5  chrI       23759  23764 (206454) + (ATAA)n      Simple_repeat      26     58    (0)   7  
   12   11.2  3.2  3.2  chrI       25029  25059 (205159) + GA-rich      Low_complexity      1     31    (0)   9  
   12   10.1  9.4  0.0  chrI       30986  31017 (199201) + (TTGTT)n     Simple_repeat       1     35    (0)  10  
   30    3.5  0.0  0.0  chrI       31117  31146 (199072) + (AT)n        Simple_repeat       1     30    (0)  11  
   20    0.0  0.0  0.0  chrI       31484  31505 (198713) + (CA)n        Simple_repeat       1     22    (0)  12  
   15    0.0  0.0  0.0  chrI       31505  31521 (198697) + (AT)n        Simple_repeat       1     17    (0)  13 *
   13   24.7  0.0  0.0  chrI       33392  33426 (196792) + (AAC)n       Simple_repeat       1     35    (0)  14  
   16   15.9  0.0  0.0  chrI       35114  35141 (195077) + A-rich       Low_complexity      1     28    (0)  15  
   18   19.9  0.0  0.0  chrI       36419  36453 (193765) + (T)n         Simple_repeat       1     35    (0)  16  
   13   24.2  0.0  5.9  chrI       42749  42802 (187416) + A-rich       Low_complexity      1     51    (0)  17  
   16    5.3  0.0  0.0  chrI       45631  45650 (184568) + (T)n         Simple_repeat       1     20    (0)  18     

我希望有一个输出,我只有chr:begin-end

我使用的代码如下

import sys
for line in open(sys.argv[1],'r'):
  columns = line.strip().split('\s')
  print columns[5]+":"+ columns[6]+"-"+columns[7]

但是我收到错误

Traceback (most recent call last):
  File "columnstrip.py", line 4, in <module>
    print columns[5]+":"+ columns[6]+"-"+columns[7]
IndexError: list index out of range

我哪里错了?在这方面,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试:

print len(line.strip().split('\s'))

并且您将获得1,因此当您尝试访问columns[6]columns[7]时,您会获得该异常。

使用.split()而不使用任何参数:

  

例如,' 1 2 3 '.split()会返回['1', '2', '3']