1

主要问题是我无法确定导致代码产生此值的原因。它应该读取文本文件中的值,然后计算值的平均置信度。但是我收到了重复的错误。这里的一个和另一个声明“无法将字符串转换为浮点数”,如果我有它告诉我它将是第一行。

我正在使用 Repl.it 运行 python,它是它的 v3。我已经尝试在我的计算机上执行此操作,我得到了类似的结果,但是,很难阅读错误,所以我将它移到那里以便看得更清楚。

# Asks usr input
usrin = input("Enter in file name: ")

# establishes variabls
count = 0

try:
  fmbox = open(usrin, 'r')
  rd = fmbox.readlines() 
  # loops through each line and reads the file
  for line in rd:
      # line that is being read

      fmLen = len(rd)
      srchD = rd.find("X-DSPAM-Confidence: ")

      fmNum = rd[srchD + 1:fmLen] # extracts numeric val
      fltNum = float(fmNum.strip().replace(' ', ''))

      #only increments if there is a value
      if (fltNum > 0.0):
          count += 1
          total = fltNum + count 

  avg = total / count

  print("The average confiedence is: ", avg)
  print("lines w pattern ", count)

返回应该是从文件中删除的数字的平均值以及有多少值大于 0 的计数。

如果您需要在此处查看 txt 文件,请访问 http://www.pythonlearn.com/code3/mbox.txt

4

1 回答 1

0

您的代码有几个问题:

  • 您正在使用列表中的find()和之类的字符串方法,而不是解析单独的行。strip()rd
  • find()如果匹配,则返回子字符串的最低"X-DSPAM-Confidence: "索引(因为似乎出现在文本文件的行首,它将返回索引 0),否则返回 -1。但是,您没有检查返回值(因此您总是假设存在匹配项),并且rd[srchD + 1:fmLen]应该是line[srchD + len("X-DSPAM-Confidence: "):fmLen-1]因为您想提取子字符串之后的所有内容,直到行尾。
  • count并且total未定义,尽管它们可能在您的代码中的其他位置
  • 使用total = fltNum + count,您将每次迭代中的总数替换为fltNum + count... 您应该在fltNum每次找到匹配项时添加到总数中

工作实施:

try:
    fmbox = open('mbox.txt', 'r')
    rd = fmbox.readlines() 
    # loops through each line and reads the file
    count = 0
    total = 0.0
    for line in rd:
            # line that is being read
            fmLen = len(line)
            srchD = line.find("X-DSPAM-Confidence: ")

            # only parse the confidence value if there is a match
            if srchD != -1:
                fmNum = line[srchD + len("X-DSPAM-Confidence: "):fmLen-1] # extracts numeric val
                fltNum = float(fmNum.strip().replace(' ', ''))

                #only increment if value if non-zero
                if fltNum > 0.0:
                        count += 1
                        total += fltNum 

    avg = total / count

    print("The average confidence is: ", avg)
    print("lines w pattern ", count)

except Exception as e:
    print(e)

输出:

The average confidence is:  0.8941280467445736
lines w pattern  1797

演示:https ://repl.it/@glhr/55679157

于 2019-04-14T19:57:28.247 回答