pythonregex将两个单词之间的文本捕获为字符串,然后附加到lis

2024-05-16 06:21:14 发布

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

这是txt文件的结构(CDS文本源的重复单位):

     CDS             311..>428
                     /gene="PNR"
                     /codon_start=1
                     /product="photoreceptor-specific nuclear receptor"
                     /protein_id="AAD28302.1"
                     /db_xref="GI:4726077"
                     /translation="METRPTALMSSTVAAAAPAAGAASRKESPGRWGLGEDPT"
 ORIGIN

我想把311..<;428到GEDPT“作为一个字符串 到目前为止,我的正则表达式是:

^{pr2}$

然后我使用循环将每个字符串添加到列表中:

for line in file:
    match = compiler.match(line)
    if match:
        list.append(str(match.group(1)))

但我总是得到一个空名单!有什么想法为什么?在

如果你能帮忙我会很感激的,我是新手!在


Tags: 文件字符串文本txtmatchline单位product
1条回答
网友
1楼 · 发布于 2024-05-16 06:21:14

我假设file是一个文件指针,比如file = open('filename.txt')。如果是这样,则使用:

for line in file:

将在换行符上打断每一行。所以前三行是:

^{pr2}$

因为每条线是分开的,所以除非合并多行线,否则将无法匹配多行模式。您可以考虑使用:

compiler = re.compile(r"^\s+CDS\s+(.+?)ORIGIN", re.DOTALL|re.MULTILINE)
fp = open('filename.txt')
all_text = fp.read()         # this reads all the text without splitting on newlines
compiler.findall(all_text)   # returns a list of all matches

相关问题 更多 >