2014-09-19 78 views
2

在我開始之前,我想要注意的是,這是家庭作業,我不想在銀盤上得到答案(不是我期望的) 。我需要我的邏輯幫助。閱讀文本文件以查找特定字符串並讀取與其相關的另一個字符串

我想做一個程序,通過文本文件位於here讀取。

一個函數需要一個參數year,並查看該年的文件,並計算當年運動員獲得的獎牌並返回總獎牌。

第二個函數以年份,運動員姓氏和名字作爲參數並報告運動員獎牌獲勝。我知道如何打開文件,以及如何使用for循環和readline命令。

我不知道如何從運動員那裏獲得獎牌的數量,如果我不直接查找數字本身。如果有人能幫助我改造我的邏輯,將不勝感激。我將發佈我的代碼以供參考。

def countByYear(year): 
line = 0 
medals = 0 
with open("athletes.txt", encoding= 'utf-8') as f: 
    for line in f: 
     s = f.readline() 
     if s == year: 
      break 
      line2 = f.readline() 
      for line2 in f: 
       if line2.isdigit(): 
        int(line2) 
        medals+=line2 
        break 
    print(medals)   
+4

第一個'break'執行後的代碼能執行嗎? – 101 2014-09-19 00:04:02

+0

爲什麼不'如果行==年? – 2014-09-19 00:08:29

+0

我認爲行是必要的計數器,我將不得不增加去下一行? – darksoulsfan 2014-09-19 00:09:54

回答

0

如果你想獲得幻想,試試這個:

def parse_file(f): 
    competitors = [] 
    for line in f: 
     last, first, year, medals, _ = line.strip(), next(f).strip(), next(f).strip(), next(f).strip(), next(f) 
     competitors.append({"last":last, "first":first, 
          "year":year, "medals":medals}) 
    return competitors 

def count_by_year(year, competitors_dict): 
    # year must be a string 
    year = str(year) 
    return sum(competitor['medals'] for competitor in competitors_dict if competitor['year'] == year) 

def years_by_athlete(firstname, lastname, year, competitors_dict): 
    for competitor in competitors_dict: 
     if competitor['first'] == firstname and \ 
      competitor['last'] == lastname and \ 
      competitor['year'] == year: 
      return competitor['medals'] 
    return None 

if __name__ == "__main__": 
    with open('path/to/your/file', 'r') as f: 
     competitors = parse_file(f) 
    num_medals_by_year = count_by_year(1900, competitors) 
    num_medals_by_athlete = years_by_athlete("DARIA", "PRATT", "1900", competitors) 

記住,文件對象在Python迭代器,所以如果你正在讀文件描述如下:

This is the first line 
This is the second line 
This is the third line 
This is the fourth line 
This is a blank line 

那麼你可以做

for line in file: 
    firstline = line 
    secondline = next(file) 
    thirdline = next(file) 
    fourthline = next(file) 
    _ = next(file) 

內置的next推進迭代器。代碼以5行塊的形式貫穿整個文件,將最後一行分配給_(這是「我們不使用這個」的常見Python成語,例如for _ in range(10)做了10次)。然後我們建立一個字典列表,以便稍後參考。這比我們每次查看文件時讀取文件要快得多。我們使用strip(除了我們扔掉的線以外,因爲......爲什麼要打擾?)來刪除尾隨的空格。這包括在每行末尾的換行符(如匹配的文件讀取This is the first line準確,你就必須尋找"This is the first line\n"

然後使用內置sum功能,我們使用一臺發電機表達式如果'year'值與我們給出的值相符,則給予每個'medals'值。這將展開到:

s = 0 
for competitor in competitors_dict: 
    if competitors_dict['year'] == year: 
     s += competitors_dict['medals'] 
return s 

至於你的第二個功能,你需要的是一系列if條件。通過competitors_dict迭代並確保'first','last''year'字段都與您的參數匹配,然後返回'medals'字段。就這麼簡單:)

+0

是的..我在聲明中意識到我的錯誤。它需要這些參數並且獲得該運動員特別贏得的獎牌。 – darksoulsfan 2014-09-19 00:26:18

+0

@darksoulsfan我明白了。我已經用第二個問題的冗長描述和函數定義編輯了我的代碼 – 2014-09-19 00:33:21

相關問題