1
  • I have written a code that extracts floating point numbers from a text file and produces a list of the numbers.

  • My challenge is summing the consecutive numbers and finding the average of the numbers.

  • I am not allowed to use the sum function and I am new to python .. this the code I have written so far ,

what can I do to add through the list

fh = open(fname)
for line in fh:
    if line.startswith("X-DSPAM-Confidence:") : continue
#    print(line)
count = 0
for line in fh:
    if line.startswith("X-DSPAM-Confidence:"):
        count = count + 1
#       print(count)

for line in fh:
    if line.startswith("X-DSPAM-Confidence:"):
#       print(line)
        xpos = line.find(' ')
#       print(xpos)
        num = line[xpos : ]
#       print(float(num))
        fnum = float(num)       
#       print(fnum)
        
        total = 0
        for i in fnum:
            total += int(i) 
            print(total)

Error:"float object not iterable on line 24" ... line 24 is the 4th for loop

6
  • what's the problem in the code Commented Aug 4, 2020 at 11:14
  • "float object not iterable on line 24" ... line 24 is the 4th for loop Commented Aug 4, 2020 at 11:17
  • approve my edit Commented Aug 4, 2020 at 11:19
  • the first part works, I have outputed the list .. my challenge is summing the members of the list without using the sum function .. and then find the average Commented Aug 4, 2020 at 11:20
  • 1
    Please also upload the text file sample. Commented Aug 4, 2020 at 11:23

3 Answers 3

2

First an open file is iterable only once, and your code shows 4 loops starting with for line in fh:. After first loop, the file pointer will reach the end of file, and the following loops should immediately return. For that reason with should be prefered.

Next somewhere in the loop you get a float value in fnum. Just initialize total before starting the loop, and add fnum when you get it:

total = 0
with open(fname) as fh:
    for line in fh:
        if line.startswith("X-DSPAM-Confidence:"):
    #       print(line)
            xpos = line.find(' ')
    #       print(xpos)
            num = line[xpos : ]
    #       print(float(num))
            fnum = float(num)       
    #       print(fnum)
            total += fnum
    #       print(total)

with ensures that the file will be cleanly closed at the end of the loop.

Sign up to request clarification or add additional context in comments.

Comments

1

fnum is a float. It's not an array, therefore it's not iterable and cannot be iterated in a for loop.

You probably don't need an array to determine the total and the average:

fname = "c:\\mbox-short.txt"
fh = open(fname)

count = 0
total = 0
for line in fh:
    if line.startswith("X-DSPAM-Confidence:"):
        xpos = line.find(' ')
        num = line[xpos : ]
        fnum = float(num)       
        total += fnum
        count += 1

print("Total = " + str(total))
print("Average = " + str(total / count))
print("Number of items = " + str(count))

4 Comments

print(fnum) outputs the list of 27 floating point numbers ,, how can I arrange them in an array or add through them consecutively without using the sum function. I just tried this but still says not iterable for the last for loop def figs(): print(fnum) total = 0 for i in figs: total += int(i) print(total)
On the line that it errors, fnum is equal to 0.8475.
how do I arrange the output in an array so that I can then iterate through it with a for loop
You probably don't need an array to determine the total and the average, I've updated my solution the total and average.
0

You don't have to use startsWith in this case. Better to use split for each line of the file. Each line will split all the words to a list. Then using the indexes you look for, X-DSPAM-Confidence:. If it exists then take the corresponding value of interest. In this case it is index number 1. Below is the code:

total = 0
number_of_items = 0

with open("dat.txt", 'r') as f:
    for line in f:
        fields = line.split()
        if fields != []:
            if fields[0] == "X-DSPAM-Confidence:":
                number_of_items += 1
                total += float(fields[1])

print(total)
print(number_of_items)      

avg = (total/number_of_items)    
print(avg)

I saved your data in a text file names, "dat.txt".

Hope it helps !!!

14 Comments

thanks for assisting.. there are 27 lines containing "X-DSPAM.." first code gives an error message :::TypeError: undefined is not an object (evaluating 'a.constructor')
I noticed this message comes up when I use the "with function"
my code outputs the list of 27 floating point numbers, my challenge is grouping them in an array so I can iterate through them with a for loop
@user1855085 I have modified the code and tried writing the outputs into a text file so I can read them but I encounter an error code on line 20 ...((ExternalError: todo; haven't implemented non-read opens on line 20)).. this is my new code
for line in fh: if line.startswith("X-DSPAM-Confidence:"): count = count + 1 # print(count) if line.startswith("X-DSPAM-Confidence:"): # print(line) xpos = line.find(' ') # print(xpos) num = line[xpos : ] # print(float(num)) fnum = float(num) file = open("kxk.txt", "w") data = fnum file.write(data) file.close() h = open('kxk.txt', 'r') content = list(h) total = 0 for line in content: if line > 0: total += line print(total)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.