读取文件并转换值“'list'对象上没有'find'属性”

2024-04-25 06:51:06 发布

您现在位置:Python中文网/ 问答频道 /正文

主要问题是我无法确定是什么导致代码产生这个值。它应该读取文本文件中的值,然后计算这些值的平均置信度。但我反复犯错误。一个在这里,另一个国家'不能转换成浮点字符串',如果我有它告诉我哪一行它将是第一个

我使用Repl.it来运行python,它是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


Tags: ininputifiscountlinerdfile
1条回答
网友
1楼 · 发布于 2024-04-25 06:51:06

您的代码有几个问题:

  • 您正在使用列表rd上的find()strip()等字符串方法,而不是解析单个行
  • find()如果存在匹配,则返回子字符串的最低索引(因为"X-DSPAM-Confidence: "似乎出现在文本文件中的行的开头,它将返回索引0),否则返回-1。但是,您没有检查返回值(因此您总是假设存在匹配),而且rd[srchD + 1:fmLen]应该是line[srchD + len("X-DSPAM-Confidence: "):fmLen-1],因为您希望提取子字符串之后直到行末尾的所有内容
  • counttotal没有定义,尽管它们可能在代码的其他地方
  • 使用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

相关问题 更多 >