Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法从文件中添加数字_Python_Python 3.x - Fatal编程技术网

Python 无法从文件中添加数字

Python 无法从文件中添加数字,python,python-3.x,Python,Python 3.x,我的代码有问题。 1-黄金 2-银牌 3-青铜 我想做的是计算每年获得多少枚金牌。例如,2002年,共有2枚金牌、1枚银牌和1枚铜牌 代码: 预期产出: 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 一

我的代码有问题。 1-黄金 2-银牌 3-青铜

我想做的是计算每年获得多少枚金牌。例如,2002年,共有2枚金牌、1枚银牌和1枚铜牌

代码:

预期产出:

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

一个简单的修复程序将使用迭代器并请求下一行:

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'
拆分块,并将块作为一组有关某个奖牌的数据进行处理。

此代码是错误的(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)

注意:这些应该可以,但我也没有测试。

我想我应该这样写:

>>> 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
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

您的代码查找年份,以及奖牌是否为金牌(“1”)在文件的同一行中,这不起作用。@TonySuffolk66那么我如何计算一年中的金牌数?请参阅我的答案-给出两个解决方案-一个试图修复代码,另一个给出更好的解决方案。快速提问,打印金牌时,如何删除(“”)?比如('Gold Carners',2)。我添加了一个导入,以按照您想要的方式进行打印-您试图将打印作为一个函数使用,但您使用的是python 2。请仔细检查-如果您使用的是python 3,则不应该出现引号。哎呀,我现在就知道了。我使用了一个错误的版本。谢谢你的提醒。你也可以投票吗?顺便问一下,你用的是哪个版本?这两个版本的主要问题是,它们都依赖于数据的完美性、输入文件中的任何错误,它们可能会以意想不到的方式中断。如果要引入正则表达式之类的复杂内容,则需要对其进行解释,当OP被清除时,会有一个新用户。@TonySuffolk66:每行都添加了注释。+1注释-老实说:我编写python已经快3年了,除非没有其他解决方案,否则我仍然不会接近reg表达式。我发现它们几乎完全不可读(这不是python的问题,而是“托尼的大脑”的问题)。这不是你的问题,正则表达式确实不可读。
For 2002:
    Gold:   2
    Silver: 1
    Bronze: 2