2014-09-20 114 views
0

使用信息我與一般形式的TXT文件:Python的TXT文件級讀寫文件

Last Name 
First Name 
Year 
Medal (This line only contains one number either 1,2,3 meaning gold,silver,bronze respectively) 

我試圖做的是讓用戶輸入一年算多少獎牌都當年獲勝。然後還有一個功能,用戶可以輸入一個姓和名,函數應該打印出「約翰·史密斯贏得了一枚(1)金牌,1864年」

def medals(medalcount): 
    year= str(input("Please enter a year: ")) 
    with open("textfile") as f: 
      medalcount+=f.read().count(year) 
    return medalcount 

基本上我使用這個功能怎麼算很多時候,用戶輸入的字符串年份出現在txt文件中。 至於下一部分我仍然對如何實際接近它感到困惑。

例子:

Smith 
John 
1896 
1 
>>> Please enter year: 1896 
15 medals won in this year 
+0

你能舉個例子輸入?你的描述讓我感到困惑。 – Veedrac 2014-09-20 01:29:06

+0

現在你的文本文件示例看起來好像你每年每個人有一個文件。是對的嗎?你不是指具有多個這種列表的文件嗎? – Newb 2014-09-20 01:55:52

+0

是的,確切地說。我只是展示整個文件的外觀。 – Cos 2014-09-20 14:49:59

回答

0
def readFile(infilepath): 
    answer = {} 
    with open(infilepath) as infile: 
     for lastname in infile: 
      lastname = lastname.strip() 
      firstname = infile.readline().strip() 
      year = infile.readline().strip() 
      medal = infile.readline().strip() 

      if year not in answer: 
       answer[year] = {} 
      if lastname not in answer[year]: 
       answer[year][lastname] = {} 
      if firstname not in answer[year][lastname]: 
       answer[year][lastname][firstname] = {} 
      if medal not in answer[year][lastname][firstname]: 
       answer[year][lastname][firstname][medal] = 0 
      answer[year][lastname][firstname][medal] += 1 
    return answer 

def count(medalcounts): 
    year = input("What year would you like to check: ").strip() 
    answer = 0 
    for lastname in medalcounts[year]: 
     for firstname,medals in medalcounts[year][lastname].items(): 
      answer += sum(medals.values()) 
    print(answer, "medals were awarded in", year) 

    firstname = input("Enter first name: ").strip() 
    lastname = input("Enter last name: ").strip() 
    for year,yeard in medalcounts.items(): 
     medals = yeard[lastname][firstname] 
     for med,count in medals.items(): 
      print("In year", year, firstname, lastname, "won", count, '. gold silver bronze'.split()[med], "medals") 

用法:

count(readFile('path/to/file')) 
+0

我發現def count在任何時候都不會調用def readFile,它如何執行所有的檢查工作? – Cos 2014-09-20 14:47:57

+0

也是.items做什麼 – Cos 2014-09-20 14:48:46

+0

@Cos:'myDict.items()'給你一個myDict'鍵值對列表 – inspectorG4dget 2014-09-20 23:53:14