[英]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
重要提示:如果每个样本的集合中都出现了来自“基因”的任何基因,我只想在“突变”中添加0或1。 即'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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.