从.txt文件中读取数字

时间:2014-04-17 06:22:07

标签: python-2.7 numbers

我有一个文件snp.txt,其中包含如下内容:

  

rs8059032 = AG rs8061205 = AC rs31099 = AG(422,0.297812)

     

rs8059032 = AG rs8061205 = AC rs4785775 = AC(408,0.284717)

     

rs8059032 = AG rs8061205 = AC rs7189213 = AG(405,0.282821)

     

rs8059032 = AG rs8061205 = AC rs41526051 = CG(406,0.283124)

     

rs8059032 = AG rs8061205 = AC rs8057477 = CT rs4888535 = AT rs4337315 = GT(400,0.277971)

     

rs8059032 = AG rs8061205 = AC rs8057477 = CT rs4888535 = AT(411,0.287815)

     

rs8059032 = AG rs8061205 = AC rs8057477 = CT rs4337315 = GT(401,0.27886)

     

rs8059032 = AG rs8061205 = AC rs8057477 = CT(414,0.291139)

我想只获取括号中的数字以保存在new.txt文件中。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

这是python的代码。

import re

fin = open('snp.txt','r').readlines()
l = [ re.match('.*(\(.*?\))',line).group(1) for line in fin]
l = [ '%d %f\n'%eval(i) for i in l]

with open('o.txt','w') as fout:
    fout.writelines(l)
    fout.close()

如果snp.txt的内容中有空白行,请将其过滤掉。