Home > Mobile >  Finding decimal in a line in python
Finding decimal in a line in python

Time:04-12

I have a file with multiple lines like these:

hello check2check number 1235.67 thanks[4]
also 67907 another number of interest[45]

I am trying to find these numbers (float) in each line (they exist only once per line) but the last string might have integers in square brackets or an integer might exist before (as in check2check shown above)

1235.67
67907
import re

def updates (self, fileHandler,spec):
   for line in fileHandler:
      line_new = line.strip('\n')
      ll = line_new.split()
      l = len(ll)


   for i in range (l-1): 
            delay = re.search('\d*\.?\d ',i)

I keep getting this error: TypeError: expected string or bytes-like object

Is this the correct way to look for the numerical values?

CodePudding user response:

Try this:

import re

def updates (self, fileHandler,spec):
    return [map(float, re.findall('\d (\.\d )*', line)[0]) for line in fileHandler]

CodePudding user response:

This for i in range (l-1) iterates over integers.

Use

for line in fileHandler:
  match = re.search(r'(?<!\S)\d*\.?\d (?!\S)', line)
  if match:
    print(match.group())

In your class:

def updates (self, fileHandler, spec):
    results = []
    for line in fileHandler:
        match = re.search(r'(?<!\S)\d*\.?\d (?!\S)', line)
        if match:
            results.append(match.group())
    return results

Remove spec if not needed.

  • Related