Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Alright, so I am new to python and I'm as of now taking the python for everyone course (py4e). 

Our exercise 7.2 task is to do the accompanying:

7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:

X-DSPAM-Confidence:    0.8475

Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution. You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.

I keep on getting this error.

ValueError: float: Argument: . is not number on line 12

When I run this code, Line 12 which is num = float(balue) + float(num) keeps misbehaving. At the point when I eliminate the float from balue then I get another which says

TypeError: cannot concatenate 'str' and 'float' objects on line 12".

So, whether a arguments be converted into floats or else is it an only string?

1 Answer

0 votes
by (26.4k points)

Your methodology was not so terrible I would say. Nonetheless, I don't get what you planned with for balue in linez, as this is emphasizing over the characters contained in linez. What you rather would have needed float(linez). I concocted a nearby arrangement resembling this:

fname = raw_input("Enter file name: ")

print(fname)

count = 0

num = 0

with open(fname, "r") as ins:

    for line in ins:

        line = line.rstrip()

        if line.startswith("X-DSPAM-Confidence:"):

            num += float(line[20:])

            count += 1

print(num/count)

Join the python online course fast, to learn python concepts in detail and get certified.

For more details, do check out the below video tutorial...

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...