如何只输出唯一的基因id?

2024-05-14 22:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在nano内使用以下命令处理一个项目:

from Bio import SeqIO
import sys
import re 

     fasta_file = (sys.argv[1])
        for myfile in SeqIO.parse(fasta_file, "fasta"):
          if len(myfile) > 250:
           gene_id = myfile.id
           mylist = re.match(r"H149xcV_\w+_\w+_\w+", gene_id)
           print (">"+list.group(0)) 

并提供以下输出:

    >H149xcV_Fge342_r3_h2_d1
    >H149xcV_bTr423_r3_h2_d1
    >H149xcV_kN893_r3_h2_d1
    >H149xcV_DNp021_r3_h2_d1
    >H149xcV_JEP3324_r3_h2_d1
    >H149xcV_JEP3324_r3_h2_d1
    >H149xcV_JEP3324_r3_h2_d1
    >H149xcV_JEP3324_r3_h2_d1
    >H149xcV_SRt424234_r3_h2_d1
    >H149xcV_SRt424234_r3_h2_d1
    >H149xcV_SRt424234_r3_h2_d1
    >H149xcV_SRt424234_r3_h2_d1

我如何更改命令,使其为我提供唯一的:

>H149xcV_Fge342_r3_h2
>H149xcV_bTr423_r3_h2
>H149xcV_kN893_r3_h2
>H149xcV_DNp021_r3_h2
>H149xcV_JEP3324_r3_h2
>H149xcV_SRt424234_r3_h2

Tags: import命令reidsysh2myfilefasta
3条回答

您可以显式地使用类,因为\w+将匹配[a-zA-Z0-9],所以即使您有多个\w+也没关系

H149xcV_[a-zA-Z0-9]+_[a-zA-Z0-9]+_[a-zA-Z0-9]+

Regex Demo

在开发正则表达式时,尝试使用正则表达式Cheatsheet,这会有很大帮助

一个小聪明的方法:

(H149xcV(_[a-zA-z0-9]+){3})

(                   start of group 1
H149xcV             match literal text
(                   start of sub-group 1
_                   match underscore
[a-zA-Z0-9]         word with digits
+                   more than one occurrence
)                   end of sub-group 1
{3}                 should repeat 3 times 
)                   end of group 1

Regex Demo

如果您只对正则表达式匹配的一部分感兴趣,请使用组将该部分挑出:

from Bio import SeqIO
import sys
import re 

fasta_file = (sys.argv[1])
for myfile in SeqIO.parse(fasta_file, "fasta"):
    if len(myfile) > 250:
        gene_id = myfile.id
        list = re.match(r"(H149xcV_\w+_\w+)_\w+", gene_id)
        print (">"+list.group(1)) 

这会让你得到你需要的输出

您还询问了如何确保输出中没有重复项。要做到这一点,你需要保存一份你已经写过的东西的记录,这意味着它们都会被存储在内存中——如果你这样做的话,你也可以在内存中建立列表,完成后再写。这是假设您的数据集不会太大以至于无法放入内存

解决方案如下所示:

from Bio import SeqIO
import sys
import re 

fasta_file = (sys.argv[1])
# by collecting results in a set, they are guaranteed to be unique
result = set()
for myfile in SeqIO.parse(fasta_file, "fasta"):
    if len(myfile) > 250:
        gene_id = myfile.id
        m = re.match(r"(H149xcV_\w+_\w+)_\w+", gene_id)
        if m.group(1) not in result:
            print(">"+m.group(1))
        result.add(m.group(1))

另一种方法是构建result并在完成后将其打印出来,但这有一个缺点,即结果不再与原始结果的顺序相同,尽管它会快一点(因为您不再需要检查每一行是否有m.group(1) not in result

您可以使用捕获组并在替换中使用该组

为了防止不必要的回溯,可以使用否定字符类[^\W_]+从单词字符中排除下划线

(H149xcV_[^\W_]+_[^\W_]+)_[^\W_]+

Regex demo

list = re.match(r"(H149xcV_[^\W_]+_[^\W_]+)_[^\W_]+", gene_id)
print (">"+list.group(1)) 

相关问题 更多 >

    热门问题