使用正则表达式拆分标题和内容

我在文件中有以下序列文本


每个标题以“>”开头的内容行数是随机的


>XM_024446048.1 PREDICTED: Homo sapiens mannosidase alpha class 2A member 1 (MAN2A1), transcript variant X2, mRNA

CAGCCCCC

TGAGCGAC

TCCCTAATGTG

ACAGTAAAGAA

>NM_001308028.1 Homo sapiens FER tyrosine kinase (FER), transcript variant 2, mRNA

CAGCCC

CCGTGACGC

GGGGTGGTGACT

GGCTC

GGTGGT

GTGAC

>NM_0013082323028.1 H STZ mRSN1A

CAGCCC

CCGTGACGC

GGG

GTGGTGA

CTGGCTCCGGAGT

CTGAGGGGTTCGG

我想以下列格式创建一个嵌套的字典:



nested_dict = { 'sequence1': {


'header': 'XM_024446048.1 PREDICTED: Homo sapiens mannosidase alpha class 2A member 1 (MAN2A1), transcript variant X2, mRNA',

'content': 'CAGCCCCCTGAGCGACTCCCTAATGTGACAGTAAAGAA'



},

               'sequence2': {


'header': 'NM_001308028.1 Homo sapiens FER tyrosine kinase (FER), transcript variant 2, mRNA',

'content': 'CAGCCCCCGTGACGCGGGGTGGTGACTGGCTCGGTGGTGTGAC'



},


               'sequence3': {


'header': 'NM_0013082323028.1 H STZ mRSN1A',

'content': 'CAGCCCCCGTGACGCGGGGTGGTGACTGGCTCCGGAGTCTGAGGGGTTCGG'



}


我被正则表达式困住了,有人可以帮助我吗?


慕森王
浏览 195回答 1
1回答

蝴蝶刀刀

你可以用^>(?P<header>[^\n()]*&nbsp; &nbsp; (?:\((?P<name>[^\n()]+)\))?[^()\n]*)[\n\r](?P<content>[\s\S]+?)(?=^>|\Z)使用multiline和verbose标志,请参阅regex101.com 上的演示。在Python:rx = re.compile(r'''&nbsp; &nbsp; ^>&nbsp; &nbsp; (?P<header>&nbsp; &nbsp; [^\n()]*&nbsp; &nbsp; &nbsp; &nbsp; (?:\((?P<name>[^\n()]+)\))?&nbsp; &nbsp; [^()\n]*&nbsp; &nbsp; )&nbsp; &nbsp; [\n\r]&nbsp; &nbsp; (?P<content>[\s\S]+?)(?=^>|\Z)''', re.M | re.X)sequences = {"sequence{}".format(idx):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{"header": m.group('header'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "content": m.group("content"),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "name": m.group('name')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for idx, m in enumerate(rx.finditer(data), 1)}print(sequences)这产生{'sequence1': {'header': 'XM_024446048.1 PREDICTED: Homo sapiens mannosidase alpha class 2A member 1 (MAN2A1), transcript variant X2, mRNA', 'content': 'CAGCCCCC\nTGAGCGAC\nTCCCTAATGTG\nACAGTAAAGAA\n', 'name': 'MAN2A1'}, 'sequence2': {'header': 'NM_001308028.1 Homo sapiens FER tyrosine kinase (FER), transcript variant 2, mRNA', 'content': 'CAGCCC\nCCGTGACGC\nGGGGTGGTGACT\nGGCTC\nGGTGGT\nGTGAC\n', 'name': 'FER'}, 'sequence3': {'header': 'NM_0013082323028.1 H STZ mRSN1A', 'content': 'CAGCCC\nCCGTGACGC\nGGG\nGTGGTGA\nCTGGCTCCGGAGT\nCTGAGGGGTTCGG', 'name': None}}在 ideone.com 上查看演示。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go