2017-06-20 69 views
1

我正在写一个程序,从一个文件接受输入,每一行可能包含“ATG”或“GTG”,我很确定我做了一切正确的事情,尽可能我正在尝试做什么。 IT是我第一次在Python中使用一个生成器,并在研究这个问题后,我仍然不知道为什么我要停止迭代。为此,我的生成器必须产生一个元组,其中每个字符串中都有ATG或GTG的起始位置。不知道为什么我得到StopIteration错误

import sys 

import p3mod 


gen = p3mod.find_start_positions() 
gen.send(None) # prime the generator 

with open(sys.argv[1]) as f: 
    for line in f: 
     (seqid,seq) = line.strip().lower().split() 
     slocs = gen.send(seq) 
     print(seqid,slocs,"\n") 

gen.close() ## added to be more official 

这是发电机

def find_start_positions (DNAstr = ""): 

    DNAstr = DNAstr.upper() 

    retVal =() 
    x = 0 
    loc = -1 

    locations = [] 

    while (x + 3) < len(DNAstr): 

     if (DNAst[x:x+3] is "ATG" or DNAstr[x:x+3] is "GTG"): 
      loc = x 

     if loc is not -1: 
      locations.append(loc) 

     loc = -1 

    yield (tuple(locations)) 

这是错误:

Traceback (most recent call last): 
    File "p3rmb.py", line 12, in <module> 
    slocs = gen.send(seq) 
StopIteration 
+0

有没有打印出来,显示每行回溯? – JacobIRR

+0

Traceback(最近一次调用最后一个):文件“p3rmb.py”,第12行,在 slocs = gen.send(seq) StopIteration –

+0

如果您调用'send',需要将yield分配给一个值。 –

回答

2

你做了一个发电机,在一次返回的所有数据。 您应该在每次迭代中产生数据。此代码可能不完美,但它可能解决您的部分问题:

def find_start_positions (DNAstr = ""): 
    DNAstr = DNAstr.upper() 

    x = 0 
    loc = -1 

    while x + 3 < len(DNAstr): 
     if DNAst[x:x+3] == "ATG" or DNAstr[x:x+3] == "GTG" : 
      loc = x 

     if loc is not -1: 
      yield loc 

     loc = -1 

StopIteration不是错误。这是发电机发出信号表明它耗尽了所有数据的方式。你只需要“尝试除了”或者在你已经为你做过的forloop中使用你的发电机。 尽管他们并不复杂,但可能需要一些时间才能习惯这些“奇怪”的错误。 ;)

+1

不要使用'is'来比较字符串。 –

+1

@ juanpa.arrivillaga好男人!没有注意到,完全集中在发电机的东西。谢谢! –

+0

可变DNAstr是否每次更改gen.send()在主函数中使用? –

2

您的生成器的生命周期内只返回一个值。它循环遍历while循环,找到所有locations,并一次返回整个列表。因此,当您第二次致电send时,您已经耗尽了发电机的运行。

你需要弄清楚你对每次调用send的期望;配置你的循环产生那么多,然后yield那导致......并且继续为未来send调用做。您的yield声明必须位于循环内才能生效。

Jayme在他的回答中给了你一个很好的例子。

0

有一个内置的find()函数来查找给定字符串中的子字符串。在这里真的需要一台发电机吗?

相反,你可以尝试:

import sys 

with open(sys.argv[1]) as f: 
    text = f.read() 

for i, my_string in enumerate(text.strip().lower().split()): 
    atg_index = my_string.find('atg') 
    gtg_index = my_string.find('gtg') 
    print(i, atg_index, gtg_index, my_string) 
+0

我希望它是一项任务 –

相关问题