简体   繁体   English

从文件读取数据,使用python添加和查找数据百分比

[英]Reading data from file, adding and finding percentage of data using python

Here is the lesson i am trying to do: "Create a program that reads all of the numbers stored in a file and calculates the total (sum) then displays the value as total points to screen. Next, have the program calculate the average score then display the value as percent score to screen. Next, make sure the program handles IOError and ValueError exceptions. I have tried about a dozen different ways using loops but cannot get anything to work. The only way i can make it work is by doing it like this: 这是我要尝试的课程:“创建一个程序,该程序读取文件中存储的所有数字并计算总和(总和),然后将该值显示为要显示的总点数。接下来,让该程序计算平均分数然后将值显示为百分比分数显示在屏幕上。接下来,确保程序处理IOError和ValueError异常。我已经尝试了使用循环的十几种不同方法,但是什么也无法工作。我唯一能使它工作的方法是像这样:

def main ():
infile = open('numdata.txt', 'r')
num1 = int(infile.readline())
num2 = int(infile.readline())
num3 = int(infile.readline())
num4 = int(infile.readline())
num5 = int(infile.readline())
num6 = int(infile.readline())
num7 = int(infile.readline())
num8 = int(infile.readline())
infile.close()
total = num1+num2+num3+num4+num5+num6+num7+num8
average = total/8
print('the total: ', total)
print('the average: ', average)

main()

Here's the best I could come up with: 这是我能想到的最好的方法:

def main():
    total = 0

    try:
        NumberFile = open('numdata.txt', 'r')

        for line in NumberFile:
            amount = float(line)
            total += amount
            print(format(total, ',.2f'))

        print('Total: ', format (total, ',.2f'))

    except ValueError:
        print('Non-numeric data found in the file.')

    except IOError:
        print('An error occured trying to read the file.')

    except:
        print('An error has occured.')

    finally:
        NumberFile.close()                      

main()

This is what i get for the output: 78.00, 171.00, 256.00, 356.00, 437.00, 513.00, 607.00, 684.00, Non-numeric data found in the file. 这是我得到的输出:78.00、171.00、256.00、356.00、437.00、513.00、607.00、684.00,在文件中找到非数字数据。

If anyone wants to show me an example of how to use a loop to do the addition i'd be very grateful. 如果有人想给我看一个如何使用循环来做加法的例子,我将不胜感激。 The numbers from the file are: 78 93 85 100 81 76 94 77 However, using 1-8 will do the trick. 文件中的数字为:78 93 85 100 81 76 94 77但是,使用1-8可以解决问题。 Any and all help is appreciated. 任何和所有帮助表示赞赏。 I'm very new to this so I'm sure there is a much easier way to do it then what I've been trying. 我对此很陌生,因此我敢肯定,比我一直在尝试的方法要容易得多。 I've tried going off examples fROm the book I'm using and none work even though I'm copying them word for word. 我尝试从正在使用的书中摘掉示例,即使我逐字逐句地复制它们,也没有用。 I've tried video examples as well and even though I copy everything exactly I still could not get loops to work. 我也尝试过视频示例,即使我完全复制了所有内容,我仍然无法使循环正常工作。 Super frustrating. 超级令人沮丧。 Here's an example i tried to use but didn't work: the numbers will just be 1,2,3 for simplicity. 这是我尝试使用的示例,但是没有用:为简单起见,数字仅为1,2,3。 These are in a .txt file called 06_tips 这些位于名为06_tips的.txt文件中

tipfile = open('06_tipfile.txt', 'r')
strRead = tipfile.readline()
ftTotalTips = float(strRead)
while strRead != '':
strRead = tipfile.readline()
if strRead != '':
    ftTotalTips = float(ftTotalTips) + float(strRead)
print('Total tips are: ', format(ftTotalTips,'.2f'))

so that should work right? 这样应该行吗? It doesn't for me. 不适合我

There were a bunch of similar of examples I tried but zero worked, so if anyone wants to provide me with the answer to my problem that'd be awesome, thanks :) 我尝试了很多类似的例子,但是零的例子起作用了,所以如果有人想为我提供解决问题的答案,那就太好了,谢谢:)

Try this snippet: 试试以下代码片段:

def is_float(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

def get_nums(infile):
    with open(infile, 'r') as f:
        return [float (x) for x in f.read().splitlines() if is_float(x)]

def main():

    nums = get_nums('numdata.txt')
    if nums:
        total = sum(nums)
        avg   = total / len(nums)

        print('The total: ', total)
        print('The average: ', avg)
    else:
        print('No numbers found in the textfile')

if __name__ == '__main__':
    main()

Hope it helps! 希望能帮助到你!

Here's a basic example to get you started. 这是一个入门的基本示例。 Instead of hard-coding how many numbers will be read from the file, you could read all the lines in the file with file.readlines() which returns a list, and lists have the length method: 您可以使用file.readlines()读取文件中的所有行,而不用硬编码从文件中读取多少个数字,该文件返回一个列表,并且列表具有length方法:

import sys

def main ():
    nums = []
    with open('numdata.txt', 'r') as data:
        for d in data.readlines():
            try:
                nums.append(int(d.strip('\n')))
            except IOError:
                print("got IOError")
                sys.exit()
            except ValueError:
                print("got ValueError")
                sys.exit()

    total = sum(nums)
    average = total/len(nums)
    print('the total: ', total)
    print('the average: ', average)

main()

The exception handling may need to be much more verbose, especially if the numbers in the file end up being various datatypes like float , but as for the numbers in your example, int() will work. 异常处理可能需要更加冗长,特别是如果文件中的数字最终成为各种数据类型(例如float ,但是对于您示例中的数字, int()将起作用。

I do not know how your file looks like but if your numbers are separated by new lines(\\n) then you can use this 我不知道您的文件是什么样子,但是如果您的数字用新行(\\ n)分隔,则可以使用此文件

with open("numdata.txt") as t:
     print sum(map(int, filter(None, t.read().split("\n"))))

sum - sums up the list sum-汇总列表

map - changes the numbers from string to int map-将数字从字符串更改为int

filter - takes out any empty strings (I was getting quite a few) 过滤器-取出所有空字符串(我得到了很多)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM