我有一个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()
,第二次调用它时,它返回一个空字符串。
另外,我认为您对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')]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句