在匹配跨越多行的文本时,我在使用Python正则表达式时遇到了一些问题。示例文本为('\n‘是换行符)
some Varying TEXT\n
\n
DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF\n
[more of the above, ending with a newline]\n
[yep, there is a variable number of lines here]\n
\n
(repeat the above a few hundred times).
我想捕获两件事:“some_Varying_TEXT”部分,以及在一次捕获中出现在它下面两行的所有大写文本行(稍后我可以去掉换行符)。我尝试了几种方法:
re.compile(r"^>(\w+)$$([.$]+)^$", re.MULTILINE) # try to capture both parts
re.compile(r"(^[^>][\w\s]+)$", re.MULTILINE|re.DOTALL) # just textlines
在这里有很多变种,但都不走运。最后一个似乎逐行匹配文本,这并不是我真正想要的。我能听懂第一部分,没问题,但我似乎不能听懂4-5行大写字母的文本。我希望match.group(1)为some_Varying_Text,line1+line2+line3+etc (2)为line1+line2+line3+etc,直到遇到空行。
如果有人好奇的话,它应该是组成蛋白质的一系列氨基酸。
发布于 2018-09-16 02:57:56
以下是与多行文本块匹配的正则表达式:
import re
result = re.findall('(startText)(.+)((?:\n.+)+)(endText)',input)
发布于 2009-02-25 20:59:59
如果每个文件只有一个氨基酸序列,我根本不会使用正则表达式。就像这样:
def read_amino_acid_sequence(path):
with open(path) as sequence_file:
title = sequence_file.readline() # read 1st line
aminoacid_sequence = sequence_file.read() # read the rest
# some cleanup, if necessary
title = title.strip() # remove trailing white spaces and newline
aminoacid_sequence = aminoacid_sequence.replace(" ","").replace("\n","")
return title, aminoacid_sequence
发布于 2009-02-25 20:58:29
我的偏好。
lineIter= iter(aFile)
for line in lineIter:
if line.startswith( ">" ):
someVaryingText= line
break
assert len( lineIter.next().strip() ) == 0
acids= []
for line in lineIter:
if len(line.strip()) == 0:
break
acids.append( line )
此时,您已经将someVaryingText作为字符串,并将acids作为字符串列表。您可以执行"".join( acids )
来生成单个字符串。
我发现这比多行正则表达式不那么令人沮丧(而且更灵活)。
https://stackoverflow.com/questions/587345
复制相似问题