-3

string = probability is 0.05 how can I extract 0.05 float value in a variable? There are many such strings in the file,I need to find the average probability, so I used 'for' loop. my code :

fname = input("enter file name: ")
fh = open(fname)
count = 0
val = 0
for lx in fh:
    if lx.startswith("probability"):
        count = count + 1
        val = val + #here i need to get the only "float" value which is in string
print(val)
  • Does this answer your question? [How to extract numbers from a string in Python?](https://stackoverflow.com/questions/4289331/how-to-extract-numbers-from-a-string-in-python) – bigbounty Jul 13 '20 at 03:15
  • 1
    You left out the important part: a complete example of how your string looks like. By guessing it would say it's something like `'probability 0.71'`? – timgeb Jul 13 '20 at 03:15
  • `float(lx.strip().split()[-1])` – nog642 Jul 13 '20 at 03:16

1 Answers1

0
import re
string='probability is 1'
string2='probability is 1.03'
def FindProb(string):

    pattern=re.compile('[0-9]')
    result=pattern.search(string)
    result=result.span()[0]

    prob=string[result:]
    return(prob)

print(FindProb(string2))

Ok, so. This is using the regular expression (aka Regex aka re) library

It basically sets up a pattern and then searches for it in a string. This function takes in a string and finds the first number in the string, then returns the variable prob which would be the string from the first number to the end.

If you need to find the probability multiple times then this might do it:

import re
string='probability is 1'
string2='probability is 1.03 blah blah bllah probablity is 0.2 ugggggggggggggggg probablity is 1.0'
def FindProb(string):
    amount=string.count('.')
    prob=0
    for i in range(amount):
        pattern=re.compile('[0-9]+[.][0-9]+')
        result=pattern.search(string)
        start=result.span()[0]
        end=result.span()[1]

        prob+=float(string[start:end])
        string=string[end:]
    return(prob)

print(FindProb(string2))

The caveat to this is that everything has to have a period so 1 would have to be 1.0 but that shouldn't be too much of a problem. If it is, let me know and I will try to find a way

SundyAgo
  • 63
  • 9