首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对行进行计数,提取浮点值,并计算这些值的平均值

对行进行计数,提取浮点值,并计算这些值的平均值
EN

Stack Overflow用户
提问于 2016-03-17 03:08:16
回答 3查看 1.8K关注 0票数 0

因此,我需要编写一个程序来提示输入文件名,然后打开该文件并通读该文件,查找以下形式的行:x-DSPAM-置信度: 0.8475我无法获得提取的值的总和,并计算行数并打印以显示给用户。

代码语言:javascript
复制
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))
EN

回答 3

Stack Overflow用户

发布于 2016-03-17 03:21:02

您的代码中有一个示例行,当您查看文件中的每一行时,计算的是示例行中的数字,而不是文件中的行。

所以,这就是我要做的:

代码语言:javascript
复制
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)

但我们可以让它更有效率:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2016-03-17 03:34:09

尝尝这个

代码语言:javascript
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2020-07-07 22:36:33

代码语言:javascript
复制
fname = input("Enter file name: ")
fh = open(fname)
count=0
x=0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    x=float(line.split(":")[1].rstrip())+x
    count=count+1
    
    
output=x/count
print("Average spam confidence:",output)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36044858

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档