切片时,代码不起作用

时间:2017-04-30 15:03:00

标签: string python-2.7 slice

我正在为Coursera python课程做作业,我不知道为什么我得到了错误。

代码用于从名称为“mbox-short.txt”的文件中的行中提取数字,然后找到这些数字的平均值。我知道该怎么做,但是当我运行它时,第14行(num = text [x:x + 6])出现“输入错误”错误。

这是我的代码:

使用文件名mbox-short.txt作为文件名

fname = raw_input("Enter file name: ")
fh = open(fname)
n = 0
total = 0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    text = line.strip()
    print text
    x = text.find('0')
    x = int(x)
    print x
    num = text[x:x+6]
    num = float(num)
    print num
    total = total + num
    n = n+1
ave = total/n
print "Average spam confidence:", ave

请帮助我:(

1 个答案:

答案 0 :(得分:0)

我刚刚重新输入它,它现在有效。最愚蠢的解决方案。无法相信。