在序列中查找某些基的正则表达式

2024-09-30 12:32:36 发布

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

在我的代码中,我要做的是清理FastA文件,只在输出字符串中包含字母a、C、T、G、N和U。我试图通过一个正则表达式来实现这一点,如下所示:

newFastA = (re.findall(r'A,T,G,C,U,N',self.fastAsequence)) #trying to extract all of the listed bases from my fastAsequence.
        print (newFastA)

然而,我并没有得到所有的基地发生秩序。我认为我的正则表达式的格式不正确,所以如果你能告诉我我犯了什么错误,那就太好了。在


Tags: 文件ofto字符串代码selfre字母
3条回答
print re.sub("[^ACTGNU]","",fastA_string)

你会得到无数个答案

或没有re

^{pr2}$

你需要使用一个字符集。

re.findall(r"[ATGCUN]", self.fastAsequence)

您的代码查找文本"A,T,G,C,U,N",并输出所有出现的文本。regex中的字符集允许以下类型的搜索:ATGCUN”,而不是“下面的:A,T,G,C,U,N

我会完全避免使用正则表达式。您可以使用str.translate删除不需要的字符。

from string import ascii_letters

removechars = ''.join(set(ascii_letters) - set('ACTGNU'))

newFastA = self.fastAsequence.translate(None, removechars)

演示:

^{pr2}$

如果还想删除空白,可以将string.whitespace放入removechars

旁注,以上仅适用于Python2,在Python3中还有一个附加步骤:

from string import ascii_letters, punctuation, whitespace

#showing how to remove whitespace and punctuation too in this example
removechars = ''.join(set(ascii_letters + punctuation + whitespace) - set('ACTGNU'))

trans = str.maketrans('', '', removechars)

dna.translate(trans)
Out[11]: 'ACTAGAGAUACCACGGNUGNUGNU'

相关问题 更多 >

    热门问题