2016-11-27 82 views
0

新程序員在這裏。所以在下面的代碼中,「year1」集合就像它應該的那樣工作,並且吐出了一些年頭。雖然當我嘗試爲「年2」做同樣的事情時,它向我吐出的唯一東西是「set()」。不確定爲什麼我的代碼正在吐出一個空集

我在想這是什麼使代碼,這是怎麼回事?感謝您提前提供任何幫助!

def compare(word1, word2, startDate, endDate): 
    with open('all_words.csv') as allWords: 
     readWords = csv.reader(allWords, delimiter=',') 
     year1 = set() 
     for row in readWords: 
      if int(startDate) <= int(row[1]) < int(endDate): 
       if row[0] == word1: 
        year1.add(row[1]) 
     year2 = set() 
     for row in readWords: 
      if int(startDate) <= int(row[1]) < int(endDate): 
       if row[0] == word2: 
        year2.add(row[1]) 
+0

您的'if'語句看起來很奇怪。你確定你想要嗎?你正在將'Bool'轉換爲'int',這是'0'或'1'。 –

+1

在readWords'循環中爲行添加'print(row)'。我認爲'readWords'一旦被遍歷一次就被消耗,在這種情況下,沒有東西會打印來確認它 – roganjosh

回答

0

如前所述,你不能沒有重置它遍歷文件兩次。您的流程中有重複的代碼 - 您可以將重複數據排除並重復一次。

def compare(word1, word2, startDate, endDate): 
    with open('all_words.csv') as allWords: 
     readWords = csv.reader(allWords, delimiter=',') 
     year1 = set() 
     year2 = set() 
     for row in readWords: 
      if int(startDate) <= int(row[1]) < int(endDate): 
       if row[0] == word1: 
        year1.add(row[1]) 
       if row[0] == word2: 
        year2.add(row[1]) 
2

在點,爲您打造您已經閱讀整個文件(你在它的結束)year2。所以你應該seek()到文件的開頭再次通過它。所以:

.... 
allWords.seek(0) 
year2 = set() 
.... 
相關問題