パイプで分割し、最初の;|
まですべてをスキップします。gb
次の要素は ID です。
from itertools import dropwhile
text = iter(text.split('|'))
next(dropwhile(lambda s: s != 'gb', text))
id = next(text)
デモンストレーション:
>>> text = '>gi|124486857|ref|NP_001074751.1| inhibitor of Bruton tyrosine kinase [Mus musculus] >gi|341941060|sp|Q6ZPR6.3|IBTK_MOUSE RecName: Full=Inhibitor of Bruton tyrosine kinase; Short=IBtk >gi|148694536|gb|EDL26483.1| mCG128548, isoform CRA_d [Mus musculus] >gi|223460980|gb|AAI37799.1| Ibtk protein [Mus musculus]'
>>> text = iter(text.split('|'))
>>> next(dropwhile(lambda s: s != 'gb', text))
'gb'
>>> id = next(text)
>>> id
'EDL26483.1'
つまり、正規表現は必要ありません。
これをジェネレーター メソッドにして、すべての ID を取得します。
from itertools import dropwhile
def extract_ids(text):
text = iter(text.split('|'))
while True:
next(dropwhile(lambda s: s != 'gb', text))
yield next(text)
これは与える:
>>> text = '>gi|124486857|ref|NP_001074751.1| inhibitor of Bruton tyrosine kinase [Mus musculus] >gi|341941060|sp|Q6ZPR6.3|IBTK_MOUSE RecName: Full=Inhibitor of Bruton tyrosine kinase; Short=IBtk >gi|148694536|gb|EDL26483.1| mCG128548, isoform CRA_d [Mus musculus] >gi|223460980|gb|AAI37799.1| Ibtk protein [Mus musculus]'
>>> list(extract_ids(text))
['EDL26483.1', 'AAI37799.1']
または、単純なループで使用できます。
for id in extract_ids(text):
print id