[英]Python: Reading a file and calculating sum and average
問題是逐行讀取文件,然后計算並顯示文件中所有有效數字的總和和平均值。
文本文件是
contains text
79.3
56.15
67
6
text again
57.86
6
37.863
text again
456.675
到目前為止,這就是我所擁有的。
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
使用with
符號可以使處理文件更加直觀。
例如,將打開和關閉更改為此:
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
可能會讓您開始
如果您想變得更聰明一點,有一個方便的python函數叫做isdigit
,它檢查字符串是否都是整數值,它可以讓您執行以下非常聰明的操作:
is_number = lambda number: all(number.split('.').isdigit())
answer = [float(line) for line in open('fileofnumbers.txt') if is_number(line)]
然后,求和和平均就變得微不足道了:
print sum(answer) # Sum
print sum(answer)/len(answer) #Average
讓我們嘗試使用try-except
列出理解。 這可能是一個矯kill過正的方法,但肯定是一個可以放在口袋中的好工具,首先,您需要編寫一個使錯誤消失的函數,例如http://code.activestate.com/recipes/576872-exception-handling-in-a -單行/ 。
然后,您可以像在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]:
sum: 336.475255142
avg: 30.5886595584
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.