无法添加文件中的数字

时间:2014-09-20 20:21:36

标签: python python-3.x

我遇到了代码问题。 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

textfile:

WHEELER
ADAM
2001
3

KHUSHTOV
ASLANBEK
2002
1

LOPEZ
MIJAIN
2002
1

BAROEV
KHASAN
2002
2

BAROEV
KHASAN
2002
3

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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'分开,并将这些块作为一组有关某枚奖牌的数据进行处理。

答案 2 :(得分: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)

注意:这些应该没问题,但我还没有测试过。

答案 3 :(得分: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