2016-03-16 66 views
0

因此,我需要编写一个程序,提示输入文件名,然后打开该文件并读取文件,查找表单行: X-DSPAM-Confidence:0.8475 我一直在获取提取值的总和并计算行数并打印以显示用户。计算行数并提取浮点值并计算值的平均值

out_number = 'X-DSPAM-Confidence: 0.8475' 
Num = 0.0 
flag = 0 
fileList = list() 

fname = input('Enter the file name') 
try: 
    fhand = open(fname) 
except: 
    print('file cannot be opened:',fname) 

for line in fhand: 
    fileList = line.split() 
    print(fileList) 
    for line in fileList: 

if flag == 0: 
    pos = out_number.find(':') 
    Num = out_number[pos + 2:] 
    print (float(Num)) 
+2

不知道和粘贴错误,但没有什么在你的for循环'为fileline' – LBaelish

回答

0

你在你的代码的例子线,当你通过在文件中的每一行,你计算在你的榜样行的数量,而不是从文件中的行。

所以,这里是我会做什么:

import os 
import sys 

fname = input('Enter the file name: ') 
if not os.path.isfile(fname): 
    print('file cannot be opened:', fname) 
    sys.exit(1) 

prefix = 'X-DSPAM-Confidence: ' 
numbers = [] 
with open(fname) as infile: 
    for line in infile: 
     if not line.startswith(prefix): continue 
     num = float(line.split(":",1)[1]) 
     print("found:", num) 
     numbers.append(num) 
    # now, `numbers` contains all the floating point numbers from the file 
average = sum(numbers)/len(numbers) 

但是我们可以让它更高效:

import os 
import sys 

fname = input('Enter the file name: ') 
if not os.path.isfile(fname): 
    print('file cannot be opened:', fname) 
    sys.exit(1) 

prefix = 'X-DSPAM-Confidence: ' 
tot = 0 
count = 0 

with open(fname) as infile: 
    for line in infile: 
     if not line.startswith(prefix): continue 
     num = line.split(":",1)[1] 
     tot += num 
     count += 1 
print("The average is:", tot/count) 
0

如果这仅仅是一个切试试这个

import re 
pattern = re.compile("X-DSPAM-Confidence:\s(\d+.\d+)") 
sum = 0.0 
count = 0 
fPath = input("file path: ") 
with open('fPath', 'r') as f: 
    for line in f: 
     match = pattern.match(line) 
     if match is not None: 
      lineValue = match.group(1) 
      sum += float(lineValue) 
      count += 1 
print ("The average is:", sum /count)