How do I extract floating point values from .txt file to use for calculation in python?

Question:

count = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
    if line.startswith("X-DSPAM-Confidence:") :
        print(line)
        count = count + 1
print(count)

There is a file with 27 lines like X-DSPAM-Confidence : 0.xxxxx, I need to extract the numerical value from each of them to be used for calculations.

Asked By: Avinav Sharma

||

Answers:

Try to use split(':'):

Code:

count = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
    if line.startswith("X-DSPAM-Confidence:") :
        print(line)
        value = line.split(':')[-1]  # will split line into 'X-DSPAM-Confidence' and 'value'
        # if you have ',' at the end of the line, simply do this:
        value = value.strip(',')
        value = float(value)
        print(value)
        count = count + 1
print(count)
Answered By: trsvchn

As long as the format is exactly as you described it, you can use the code below:

float(line.split(':')[1])

If there’s more variation in the text than what you described, you might need to try regex.

Answered By: Allen

You can use str.rfind(':') to get the position of : and then do a string slice to get the value.

count = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
    if line.startswith("X-DSPAM-Confidence:") :
        print(line)
        value = line[line.rfind(':'):]  # will take the last occurrence of : to slice the line
        print(value)
        count = count + 1
print(count)
Answered By: ycx
fname = input("Enter file name: ")
fh = open(fname)
count = 0
pos = 0
ans = None
total = 0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : 
        continue
    else :
        count = count + 1
        pos = line.find(':')
        ans = line[pos+1 : ]
        total = total + float(ans)
avg = total/count
Answered By: Taj99
fname = input("Enter file name: ")
fh = open(fname)
val = 0
count = 0
for line in fh:
    if line.startswith("X-DSPAM-Confidence:") :
        count = count + 1
        val=val + float(line[line.find('0'):])
    elif not line.startswith("X-DSPAM-Confidence:") :
        continue
print("Average spam confidence:",val/count)
Answered By: Kranthi Chaithanya
fname = input("Enter file name:")
fh = open(fname)
count = 0
s=0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:"):
        continue
    count = count+1
    pos = line.find('0')
    floatingP = float(line[pos:])
    s += floatingP
print(s/count)
Answered By: Mohsen

use count and sum then sum/count
enter image description here

Answered By: user19887190
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.