2016-09-17 73 views
0

我遇到了計算文件中數字平均值的問題。 到目前爲止,我已經做了一個函數,讀入文件並計算行數。 該文件由多列數字組成,但列8是我需要計算的列。計算文件中數字的平均值

def file_read(): 
    fname = input("Input filname: ") 
    infile = open(fname,'r') 
    txt = infile.readlines() 
    print("opens",fname,"...") 

num_lines = sum(1 for line in open(fname)) 

#The first line in the file is only text, so i subtract 1 
print("Number of days:",(num_lines-1)) 

這些數字也是小數,所以我使用浮點數。

這是我的計算總和的數字, 應除以行數,但我來了一個錯誤,因爲第一行是文本。

with open(fname) as txt: 
     return sum(float(x) 
       for line in txt 
       for x in line.split()[8] 

有沒有辦法讓我的Python可以忽略第一行,只專注於下面的數字?

+0

沒有得到你的問題,你想在文件或文件只是數字來計算的「行」數的平均值? –

+0

只是爲了說清楚我想計算數字的平均值 –

回答

0

你可以使用txt.readline()讀的第一線,但隨着迭代的方式做到這一點堅持,剛落上使用文件迭代的第一行與next

with open(fname) as txt: 
    next(txt) # it returns the first line, we just ignore the return value 
    # your iterator is now on the second line, where the numbers are 
    for line in txt: 
     ... 

邊注:這也是非常有用的跳過使用csv模塊打開的文件的標題行,這是因爲csv標題可以位於多行,因此next優於readline

0

試試這個

import re 
#regular expression for decimals 
digits_reg = re.compile(r"\d+\.\d+|\d+") 

with open('''file name''', "r") as file: 
    allNum = [] 
    #find numbers in each line and add them to the list 
    for line in file: 
     allNum.extend(digits_reg.findall(line)) 

#should be a list that contains all numbers in the file 
print(alNum)