简体   繁体   English

Python:读取文件并计算总和和平均值

[英]Python: Reading a file and calculating sum and average

The question is to read the file line by line and calculate and display the sum and average of all of the valid numbers in the file. 问题是逐行读取文件,然后计算并显示文件中所有有效数字的总和和平均值。

The text file is 文本文件是

contains text
79.3
56.15
67
6
text again 
57.86
6
37.863
text again 
456.675

That's all I have so far. 到目前为止,这就是我所拥有的。

numbers = open('fileofnumbers.txt', 'r')

line = file_contents.readline()

numbers.close()

try:
    sum = line + line
    line = file_contents.readline()
    print "The sum of the numbers is", sum


except ValueError:
    print line

Using with notation can make dealing with files a lot more intuitive. 使用with符号可以使处理文件更加直观。

For instance, changing the opening and closing to this: 例如,将打开和关闭更改为此:

summation = 0

# Within the with block you now have access to the source variable
with open('fileofnumbers.txt', 'r') as source:
    for line in source: #iterate through all the lines of the file 
        try:
            # Since files are read in as strings, you have to cast each line to a float
            summation += float(line)
        except ValueError:
            pass

Might get you started 可能会让您开始

If you want to be a little more clever, there's a convenient python function called isdigit , which checks if a string is all integer values, which can let you do very clever things like this: 如果您想变得更聪明一点,有一个方便的python函数叫做isdigit ,它检查字符串是否都是整数值,它可以让您执行以下非常聪明的操作:

is_number = lambda number: all(number.split('.').isdigit())
answer = [float(line) for line in open('fileofnumbers.txt') if is_number(line)]

Which then makes sum and average trivial: 然后,求和和平均就变得微不足道了:

print sum(answer) # Sum
print sum(answer)/len(answer) #Average

Let's try list comprehension with try-except . 让我们尝试使用try-except列出理解。 This might be an overkill but surely a good tool to keep in your pocket, first you write a function that will silence the errors as such in http://code.activestate.com/recipes/576872-exception-handling-in-a-single-line/ . 这可能是一个矫kill过正的方法,但肯定是一个可以放在口袋中的好工具,首先,您需要编写一个使错误消失的函数,例如http://code.activestate.com/recipes/576872-exception-handling-in-a -单行/

Then you can use list comprehension by passing in argv like you do in Unix: 然后,您可以像在Unix中一样通过传入argv来使用列表argv

intxt = """contains text
29.3423
23.1544913425
4
36.5
text again 
79.5074638
3
76.451
text again 
84.52"""

with open('in.txt','w') as fout:
    fout.write(intxt)

def safecall(f, default=None, exception=Exception):
    '''Returns modified f. When the modified f is called and throws an
    exception, the default value is returned'''
    def _safecall(*args,**argv):
        try:
            return f(*args,**argv)
        except exception:
            return default
    return _safecall

with open('in.txt','r') as fin:
    numbers = [safecall(float, 0, exception=ValueError)(i) for i in fin] 
    print "sum:", sum(numbers)
    print "avg:", sum(numbers)/float(len(numbers))

[out]: [OUT]:

sum: 336.475255142
avg: 30.5886595584

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

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