主要问题是我无法确定是什么导致代码产生这个值。它应该读取文本文件中的值,然后计算这些值的平均置信度。但我收到了重复的错误。这里的一个和另一个声明“无法将字符串转换为 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]
因为您想要提取子字符串之后直到行尾的所有内容。 -
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
关于python - 读取文件并转换值 "'列表'对象没有属性 'find'”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679157/