Am编写一个提示输入文件名的程序,然后打开该文件并读取文件,查找表单行:
X-DSPAM-置信度:0.8475
我想计算这些线并从每条线中提取浮点值并计算这些值的平均值。我可以请一些帮助。我刚开始编程所以我需要一些非常简单的东西。这是我已编写的代码。
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname,'r')
count = 0
total = 0
#Average = total/num of lines
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
count = count+1
print line
答案 0 :(得分:1)
迭代文件(使用上下文管理器("和#34;)自动处理关闭),寻找这样的行(就像你做的那样),然后像这样读取它们:
fname = raw_input("Enter file name:")
if not fname:
fname = "mbox-short.txt"
scores = []
with open(fname) as f:
for line in f:
if not line.startswith("X-DSPAM-Confidence:"):
continue
_, score = line.split()
scores.append(float(score))
print sum(scores)/len(scores)
或者更紧凑:
mean = lambda x: sum(x)/len(x)
with open(fname) as f:
result = mean([float(l.split()[1]) if line.startswith("X-DSPAM-Confidence:") for l in f])
答案 1 :(得分:1)
尝试:
total += float(line.split(' ')[1])
以便total / count
为您提供答案。
答案 2 :(得分:0)
以下程序应满足您的需求。如果您需要更改程序要查找的内容,只需更改PATTERN
变量以描述您要匹配的内容。该代码是为Python 3.x编写的,但如果需要,可以很容易地适用于Python 2.x.
<强>程序:强>
#! /usr/bin/env python3
import re
import statistics
import sys
PATTERN = r'X-DSPAM-Confidence:\s*(?P<float>[+-]?\d*\.\d+)'
def main(argv):
"""Calculate the average X-DSPAM-Confidence from a file."""
filename = argv[1] if len(argv) > 1 else input('Filename: ')
if filename in {'', 'default'}:
filename = 'mbox-short.txt'
print('Average:', statistics.mean(get_numbers(filename)))
return 0
def get_numbers(filename):
"""Extract all X-DSPAM-Confidence values from the named file."""
with open(filename) as file:
for line in file:
for match in re.finditer(PATTERN, line, re.IGNORECASE):
yield float(match.groupdict()['float'])
if __name__ == '__main__':
sys.exit(main(sys.argv))
如果需要,您也可以按以下方式实施get_numbers
生成器。
<强>替代:强>
def get_numbers(filename):
"""Extract all X-DSPAM-Confidence values from the named file."""
with open(filename) as file:
yield from (float(match.groupdict()['float'])
for line in file
for match in re.finditer(PATTERN, line, re.IGNORECASE))