2014-09-20 82 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