2017-08-01 70 views
-1

我有一个名为50267.gff像GFF文件如下如何使用正则表达式在方括号内获取内容?

#start gene g1 
dog1 
dog2 
dog3 
#protein sequence = [DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD] 
#end gene g1 
### 
#start gene g2 
cat1 
cat2 
cat3 
#protein sequence = [CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC 
#CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC] 
#end gene g2 
### 
#start gene g3 
pig1 
pig2 
pig3 
... 

我想括号内获得内容,并命名为50267.fa像新的文件如下

>g1_50267 
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD 
>g2_50267 
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCC 
... 
+0

导入重。您可以全局使用以下正则表达式: \ [(。*?)\] –

+1

这些不是括号,它们是方括号。 – Barmar

+0

@HariomSingh方括号必须被转义 – Barmar

回答

0

可以使用\[(.*?)\]\[([^\]]+)

import re 

with open("50267.gff", "r") as ff: 
    matches = re.findall(r'\[([^\]]+)', ff.read()) 
    matches = ['>g' + str(ind+1) + "_50267\n" + x.replace('\n#', ' ') for ind, x in enumerate(matches)] 
    #print(matches) 
    with open('50267.fa', 'w') as fa: 
     fa.write("\n".join(matches)) 
+0

感谢您的帮助!我有个问题!这是什么意思? – tehoo

0

你需要逃脱方括号中的正则表达式。然后,您可以使用捕获组来获取内容。

matches = re.findall(r'\[(.*?)\]', string) 
g = 1 
for match in matches: 
    print('>g' + g + '_50267'); 
    print match[0] 
    g += 1 
相关问题