python 搜索一组词

python search for a set of words

简单来说,我正在寻找使用正则表达式而不使用 for 循环来搜索字符串中一组单词的最快方法。即有没有办法做到这一点:

text = 'asdfadfgargqerno_TP53_dfgnafoqwefe_ATM_cvafukyhfjakhdfialb'
genes = set(['TP53','ATM','BRCA2'])
mutations = 0
if re.search( genes, text):
    mutations += 1
print mutations 
>>>1

这样做的原因是因为我正在搜索一个复杂的数据结构并且不想嵌套太多循环。这是更详细的问题代码:

genes = set(['TP53','ATM','BRCA2'])
single_gene = 'ATM'
mutations = 0
data_dict = {
             sample1=set(['AAA','BBB','TP53'])
             sample2=set(['AAA','ATM','TP53'])
             sample3=set(['AAA','CCC','XXX'])
             sample4=set(['AAA','ZZZ','BRCA2'])
            }

for sample in data_dict:
    for gene in data_dict[sample] 
        if re.search( single_gene, gene):
            mutations += 1
            break

我可以轻松搜索 'single_gene',但我想搜索 'genes'。如果我添加另一个 for 循环来遍历 'genes' 那么代码将变得更加复杂,因为我将不得不添加另一个 'break' 和一个布尔值来控制中断发生的时间?从功能上讲它可以工作但是非常笨重并且必须有更优雅的方法来做到这一点?请参阅下面的设置的笨拙的额外循环(目前我唯一的解决方案):

for sample in data_dict:
    for gene in data_dict[sample] 
        MUT = False
        for mut in genes:
            if re.search( mut, gene):
                mutations += 1
                MUT = True
                break
        if MUT == True:
            break

重要提示:如果来自 'genes' 的任何基因出现在每个样本的集合中,我只想将 0 或 1 添加到 'mutations'。即 'sample2' 将为突变加 1,样本 3 将加 0。如果有任何需要进一步澄清的地方,请告诉我。提前致谢!

如果您的目标字符串是固定文本(即不是正则表达式),请不要使用 re。效率更高的是:

for gene in genes:
    if gene in text:
        print('True')

该主题有多种变体,例如:

if [gene for gene in genes if gene in text]:
    ...

读起来很混乱,包含列表理解,并且指望空列表 [] 在 Python.

中被认为是假的

因问题更改而更新:

你还在艰难地做着。考虑一下:

def find_any_gene(genes, text):
    """Returns True if any of the subsequences in genes
       is found within text.
    """
    for gene in genes:
        if gene in text:
           return True
    return False

mutations = 0
text = '...'

for sample in data_dict:
    for genes in data_dict[sample]
         if find_any_gene(genes, text):
             mutations += 1

这样的优点是缩短搜索所需的代码更少,可读性更强,并且函数 find_any_gene() 可以被其他代码调用。

这个有用吗?我使用了评论中的一些示例。

如果我很近,请告诉我?!

genes = set(['TP53','ATM','BRCA2', 'aaC', 'CDH'])
mutations = 0
data_dict = {
             "sample1":set(['AAA','BBB','TP53']),
             "sample2":set(['AAA','ATM','TP53']),
             "sample3":set(['AAA','CCC','XXX']),
             "sample4":set(['123CDH47aaCDHzz','ZZZ','BRCA2'])
            }

for sample in data_dict:
    for gene in data_dict[sample]:
        if [ mut for mut in genes if mut in gene ]:
            print "Found mutation: "+str(gene),
            print "in sample: "+str(data_dict[sample])
            mutations += 1

print mutations