如何在 python 中使用 regex(findall) 进行枚举?
how to use enumerate with regex(findall) in 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.findall
、enumerate
制作列表
以下列表是我想要得到的。
>>>print (seq)
["QWERTYUIOP","ASDFGHJKL","ZXCVBNM"]
如何修复此代码sequence=re.findall(r'name[ind][^/n]+' for ind in enumerate(name), file.read())
?
首先,您不能使用 read()
读取文件两次,第二次调用它时,它 returns 是一个空字符串。
另外,我认为你对re.findall
的理解有误。它只需要 2 个参数(正则表达式、字符串)。
您可以一次性完成任务,无需调用 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')]
我有一个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.findall
、enumerate
制作列表
以下列表是我想要得到的。
>>>print (seq)
["QWERTYUIOP","ASDFGHJKL","ZXCVBNM"]
如何修复此代码sequence=re.findall(r'name[ind][^/n]+' for ind in enumerate(name), file.read())
?
首先,您不能使用 read()
读取文件两次,第二次调用它时,它 returns 是一个空字符串。
另外,我认为你对re.findall
的理解有误。它只需要 2 个参数(正则表达式、字符串)。
您可以一次性完成任务,无需调用 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')]