4

如何在下面的“str”中获取“uniprotkb:”和“(基因名称)”之间的所有值:

str = 'uniprotkb:HIST1H3D(gene name)|uniprotkb:HIST1H3A(gene name)|uniprotkb:HIST1H3B(gene name)|uniprotkb:HIST1H3C(gene name)|uniprotkb:HIST1H3E(gene name)|uniprotkb:HIST1H3F(gene name)|uniprotkb:HIST1H3G(gene name)|uniprotkb:HIST1H3H(gene name)|uniprotkb:HIST1H3I(gene name)|uniprotkb:HIST1H3J(gene name)' 

结果是:

HIST1H3D
HIST1H3A
HIST1H3B
HIST1H3C
HIST1H3E
HIST1H3F
HIST1H3G
HIST1H3H
HIST1H3I
HIST1H3J 
4

3 回答 3

8

使用 re.findall(),您可以获得匹配正则表达式的字符串的所有部分:

>>> import re
>>> sstr = 'uniprotkb:HIST1H3D(gene name)|uniprotkb:HIST1H3A(gene name)|uniprotkb:HIST1H3B(gene name)|uniprotkb:HIST1H3C(gene name)|uniprotkb:HIST1H3E(gene name)|uniprotkb:HIST1H3F(gene name)|uniprotkb:HIST1H3G(gene name)|uniprotkb:HIST1H3H(gene name)|uniprotkb:HIST1H3I(gene name)|uniprotkb:HIST1H3J(gene name)' 
>>> re.findall(r'uniprotkb:([^(]*)\(gene name\)', sstr)

['HIST1H3D', 'HIST1H3A', 'HIST1H3B', 'HIST1H3C', 'HIST1H3E', 'HIST1H3F', 'HIST1H3G', 'HIST1H3H', 'HIST1H3I', 'HIST1H3J']
于 2012-10-02T14:54:55.550 回答
0

这是一个单行:

astr = 'uniprotkb:HIST1H3D(gene name)|uniprotkb:HIST1H3A(gene name)|uniprotkb:HIST1H3B(gene name)|uniprotkb:HIST1H3C(gene name)|uniprotkb:HIST1H3E(gene name)|uniprotkb:HIST1H3F(gene name)|uniprotkb:HIST1H3G(gene name)|uniprotkb:HIST1H3H(gene name)|uniprotkb:HIST1H3I(gene name)|uniprotkb:HIST1H3J(gene name)'
[pt.split('(')[0] for pt in astr.strip().split('uniprotkb:')][1:]

给出:

['HIST1H3D',
 'HIST1H3A',
 'HIST1H3B',
 'HIST1H3C',
 'HIST1H3E',
 'HIST1H3F',
 'HIST1H3G',
 'HIST1H3H',
 'HIST1H3I',
 'HIST1H3J']

如果运行时很重要,我不推荐正则表达式解决方案。

于 2012-10-02T14:58:45.393 回答
-1

我不会打扰正则表达式:

s = 'uniprotkb:HIST1H3D(gene name)|uniprotkb:HIST1H3A(gene name)'  # etc

gene_names = []
for substring in s.split('|'):
    removed_first = substring.partition('uniprotkb:')[2]  # remove the first part of the substring
    removed_second = removed_first.partition('(gene name)')[0]  # remove the second part
    gene_names.append(removed_second)  # put it on the list

应该做的伎俩。你甚至可以单行它 - 以上相当于:

gene_names = [substring.partition('uniprotkb:')[2].partition('(gene name)')[0] for substring in s.split('|')]
于 2012-10-02T14:55:40.763 回答