python - 读取文件并转换值 "'列表'对象没有属性 'find'”

标签 python python-3.x

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

我正在使用 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

最佳答案

您的代码存在几个问题:

  • 您正在使用字符串方法,例如 find()strip()在名单上rd而不是解析单独的行。
  • 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

关于python - 读取文件并转换值 "'列表'对象没有属性 'find'”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679157/

相关文章:

python - 当脚本可以从不同位置调用时,如何编写导入语句?

python - flask-restful 的 CORS 类型错误

python list/dict 属性最佳实践

python - 将 Json 数据转换为 Python DataFrame

arrays - Python3从列表创建数组(我认为)

python - 张量板重复标志错误

python - 我想知道一种从已知列表中的已知字母组合中查找单词的方法

python - 每个输入文件单独的测试用例?

python - 每个值多个键

python - 如何在不创建本地文件的情况下将 .xlsx 文件上传到 FTP?