如何在python中与regex(findall)一起使用enumerate?

2024-04-18 18:03:02 发布

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

我有一个txt文件如下

#onetwothree.txt
>one 
QWERTYUIOP
>two
ASDFGHJKL
>three
ZXCVBNM
...

我想把这个txt文件分成几个文件,如下所示

#one.txt
>one
QWERTYUIOP

以及

#two.txt
>two
ASDFGHJKL

以及

#three.txt
>three
ZXCVBNM

这是我的密码

import re
with open("onetwothree.txt") as file:
 name=re.findall(r'\>[^\n]+',file.read())
 sequence=re.findall(r'name[ind][^/n]+' for ind in enumerate(name), file.read())
          .
          .
          .

我知道下面的部分有问题。你知道吗

sequence=re.findall(r'name[ind][^/n]+' for ind in enumerate(name), file.read())

我想用re.findallenumerate做一个列表 下面的清单就是我想要的。你知道吗

>>>print (seq)
["QWERTYUIOP","ASDFGHJKL","ZXCVBNM"]

如何修复此代码sequence=re.findall(r'name[ind][^/n]+' for ind in enumerate(name), file.read())对吗?你知道吗


Tags: 文件nameretxtreadonefilethree
1条回答
网友
1楼 · 发布于 2024-04-18 18:03:02

首先,不能使用read()读取文件两次,第二次调用时,它返回一个空字符串。你知道吗

另外,我认为你对re.findall的理解是错误的。它只需要2个参数(regex,string)。你知道吗

您可以一次性完成任务,而无需调用findall两次。你知道吗

s = '''>one 
QWERTYUIOP
>two
ASDFGHJKL
>three
ZXCVBNM
''' # replace this with file.read()

res = re.findall(">([^\n]+)\n(\w+)",s)     #each regex in paren constitutes a group
print(res) 
#[('one ', 'QWERTYUIOP'), ('two', 'ASDFGHJKL'), ('three', 'ZXCVBNM')]

相关问题 更多 >