2013-12-12 63 views
1

我採取一個文件中,它看起來像循環列表蟒蛇不增加

12 125  "neg"  Won the match #getin . P 

,然後做句子的單詞分析標準輸入。

我不知道爲什麼,但函數「unigrams_nrc」中的循環沒有增加。 i value is still 0

下面是代碼:

def unigrams_nrc(file): 
     for line in file: 
     (term,score,numPos,numNeg) = re.split("\t", line.strip()) 
     print sentence[i] #=> prints all 0's i does not increment 
     if re.match(sentence[i],term.lower()): 
     wordanalysis["unigram"] = found 
     else: 
     found = False 
     if found: 
     wordanalysis["trail_unigram"] = found if re.match(sentence[(len(sentence)-1)],term.lower()) else not(found) 
     wordanalysis["lead_unigram"] = found if re.match(sentence[0],term.lower()) else not(found) 
     wordanalysis["nonzero_sscore"] = float(score) if (float(score) != 0) else 0    
     wordanalysis["sscore>0"] = (float(score) > 0) 
     wordanalysis["sscore"] = (float(score) != 0) 

     if re.match(tweet[len(sentence)-1],term.lower()): 
     wordanalysis["sscore !=0 last token"] = (float(score) != 0) 


for line in sys.stdin: 
    #12 125 "neg"  Won the match #getin . P 
    (tweetid,num,senti,tweets) = re.split("\t+",line.strip()) 
    sentence = re.split("\s+", tweets.strip()) 
    for i in range(0,len(sentence)): 
     unigrams_nrc(file) 

即使我在參數傳遞i的功能..仍然沒有改變。

+0

哪個功能? – aIKid

+0

unigrams_nrc是函數 – fscore

+0

它不是'我',它是0,它是'句子[我]'。 – aIKid

回答

2

縮進不正確,但假設它應該像in your other questionprint sentence[i]位於for line in file:循環內。由於i在循環內部不會增加,因此您會看到多次打印的相同內容。

當您第二次撥打unigrams_nrc時,file中沒有更多行要讀取,因此循環執行零次。要再次讀取文件,您需要關閉並打開它,或者到最初的seek。儘管如此,將數據讀入例如。一本字典,甚至只是一份清單,都會加速你的程序。

快速解決方法是在打開file後添加file = file.readlines();那麼你的代碼的其餘部分應該按原樣工作。

+0

只打印贏得'n'次數 – fscore

+0

@fscore請參閱編輯。 –

+0

是的我知道我沒有增加,但爲什麼會發生這種情況。我該如何解決這個問題。 – fscore

0

你想要做這樣的事

def foo1(): 
    print something[i] 

def foo0(): 
    for i in range(0,number): 
     foo1(somethingElse) 

這是不可能的!
foo1如何知道isentence的值?如果你想使用它們,你必須傳遞這些值。

def foo1(something,i): 
    print something[i] 

def foo0(): 
    for i in range(0,number): 
     foo1(something,i)