[英]python type error: invalid type does not support indexing
I am writing a program that finds a certain type of line from a file and finds numbers inside them and calculates their average. 我正在编写一个程序,该程序从文件中查找某种类型的行,并在其中查找数字并计算其平均值。
Here it is: 这里是:
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
I get: 我得到:
TypeError: '<Invalid Type>' does not support indexing on line 8.
I'll extend on my comment. 我继续评论。
Your code (limited to your issue) is: 您的代码(仅限您的问题)为:
fh = open(fname)
for line in fh:
x = fh[22:29]
fh
is actually a file
object, which does not support slice syntax. fh
实际上是一个file
对象,不支持切片语法。 If you want to retrieve information from line you have to actually perform operation on line. 如果要从线路中检索信息,则必须实际执行线路操作。
fh = open(fname)
for line in fh:
x = line[22:29]
You're looking at the file and not the line. 您正在查看文件而不是行。 Also, you should simplify your code.
另外,您应该简化代码。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.