我正在编写一个程序,它从文件中找到某种类型的行,并在其中查找数字并计算它们的平均值。
这是:
total = 0
count = 0
fname = raw_input("Enter file name: ")
fh = open(fname)
for line in fh:
if line.startswith('X-DSPAM-Confidence:'):
count = float(count) + 1
x = fh[22:29]
total = float(total) + float(x)
else:
continue
print total/count
我明白了:
TypeError: '<Invalid Type>' does not support indexing on line 8.
答案 0 :(得分:6)
我会继续发表评论。
您的代码(仅限于您的问题)是:
Function CountRed(range_data As Range) As Long
Application.Volatile
Dim datax As Range
For Each datax In range_data
If datax.Interior.Color = vbRed Then
CountRed = CountRed + 1
End If
Next datax
End Function
fh = open(fname)
for line in fh:
x = fh[22:29]
实际上是一个fh
对象,它不支持切片语法。如果你想从线上检索信息,你必须在线实际执行操作。
file
答案 1 :(得分:0)
你正在查看文件,而不是行。此外,您应该简化代码。
total = 0.0
count = 0.0
# Headers look like this:
# X-DSPAM-Confidence: 0.9928
dspam_header = 'X-DSPAM-Confidence:'
fname = raw_input("Enter file name: ")
with open(fname) as fh:
for line in fh:
if not line.startswith(dspam_header):
continue
count += 1
total += float(line[len(dspam_header):])
if count:
print total/count