2014-09-20 91 views
1

我遇到代碼問題。 1 - 金色 2 - 銀色 3 - 銅色無法從文件中添加數字

我想要做的是計算每年有多少枚金牌。例如,在2002年,共有2枚金牌,1枚銀牌和1枚銅牌。

代碼:

def main(): 
    year = str(input("Enter year to count its winners: ")) 
    goldmedal = 0 
    openFile = open("test.txt") 
    gold = "1" 
    for line in openFile.read().split('\n'): 
     if year in line: 
      if str(1) in line: 
       goldmedal = goldmedal + 1 
    print("Gold Medals: ", gold medal) 

預期輸出:

Enter year to count its winners: 2002 
Gold Medals: 2 

文本文件:

WHEELER 
ADAM 
2001 
3 

KHUSHTOV 
ASLANBEK 
2002 
1 

LOPEZ 
MIJAIN 
2002 
1 

BAROEV 
KHASAN 
2002 
2 

BAROEV 
KHASAN 
2002 
3 
+0

你的代碼看起來這一年,和獎牌是金( 「1」)上文件中的同一行,這不會工作。 – 2014-09-20 20:31:12

+0

@ TonySuffolk66那麼我如何計算一年的黃金數量呢? – joestuff 2014-09-20 20:34:05

+0

看到我的答案 - 給出了兩個解決方案 - 一個試圖修復你的代碼,另一個提供更好的解決方案。 – 2014-09-20 20:45:27

回答

0

此代碼是一個錯誤(tm)修復 - 它假定數據是正確的,並在找到合適的年份時設置一個標誌。這不是一個很好的解決方案:一個更好的解決方案(在我看來)是將數據首次加載到數據結構(可能是字典),然後搜索詞典

from __future__ import print_function 
def main(): 
    year = str(input("Enter year to count its winners: ")) 
    goldmedal = 0 
    found_year = False 
    openFile = open("test.txt") 
    gold = "1" 
    for line in openFile.read().split('\n'): 
     if year in line: 
      found_year = True 
      continue: 

     if found_year: 
      if gold in line: 
       goldmedal = goldmedal + 1 
      found_year = False 

print("Gold Medals: ", goldmedal) 

更好的解決辦法是這樣的:

from __future__ import print_function 
def main(): 
    winners = [] 
    with open("test.txt") as openfile: 
     surname, firstname, year, medal, blank = next(openfile), next(openfile), next(openfile), next(openfile), next(openfile) 
     winners.append({"Surname":surname,"Firstname":firstname,"Medal":medal}) 

    year = str(input("Enter year to count its winners: ")) 
    goldcount = sum([1 for winner in winners if winner.year=year and medal=1]) 
    print ("Gold Medals", goldcount) 

注意:這些應該沒問題,但我還沒有測試過。

+0

快速的問題,當打印出金牌時,我該如何刪除('')?像('金牌',2)。 – joestuff 2014-09-20 20:44:22

+0

我已經添加了一個導入來打印你想要的方式 - 你正在嘗試使用打印功能,但你使用的是Python 2. – 2014-09-20 20:46:14

+0

我正在使用Python 3 – joestuff 2014-09-20 20:48:31

0

一個簡單的修復,使用迭代器,並要求下一行:

lines = iter(openFile.read().split('\n')) 
for line in lines: 
    if year in line: 
     line = next(lines) 
     if str(1) in line: 
      goldmedal = goldmedal + 1 

一個適當的修復方法是與'\n\n'拆分並將這些塊作爲關於某個獎牌的一組數據進行處理。

1
>>> import re # Import regular expression python module 
>>> with open('in','r') as f: # Open the file 
...  text = f.read()  # Read the contents 
# Get all the years based on the regular expression, which in this case is extracts all the 4 digits and 1 digit numbers seperated by `\n` 
>>> values = re.findall(r'([0-9]{4})\n([0-9]{1})', text) 
>>> values 
[('2001', '3'), ('2002', '1'), ('2002', '1'), ('2002', '2'), ('2002', '3')] 
>>> a = raw_input('Enter year to count its winners:') # Input 
>>> b = '1' 
>>> j=(a,b) # create this tuple based on your query 
>>> output = sum([ 1 for i in year_count if i==j]) # Get the total gold for that year 
>>> print 'Gold Medals: ',output # Output 
+0

如果您要引入像正則表達式這樣複雜的東西,則需要在OP清除新用戶時解釋它們。 – 2014-09-20 20:50:11

+1

@ TonySuffolk66:爲每行添加註釋。 – g4ur4v 2014-09-20 21:00:01

+0

+1意見 - 說實話:我已經編寫了python近3年,除非沒有其他解決方案,否則我仍然不會接近reg表達式。我發現它們幾乎完全不可讀(這不是python問題,它是「Tony的大腦」問題)。 – 2014-09-20 21:07:37

0

我想我會這樣寫:

kind={1: 'Gold', 2: 'Silver', 3: 'Bronze'} 
fields=('last', 'first', 'year', 'medal') 
year='2002' 

data=[] 
with open(fn) as f: 
    txt=f.read() 
    for block in txt.split('\n\n'): 
     data.append({k:v for k, v in zip(fields, block.splitlines())}) 

counts={} 
for e in data: 
    key=int(e['medal']) 
    counts[key] = counts.setdefault(key, 0) + 1 

print('For {}:'.format(year))  
for key in counts: 
    print('\t{:7} {}'.format(kind[key]+':', counts[key])) 

打印:

For 2002: 
    Gold: 2 
    Silver: 1 
    Bronze: 2