Home > OS >  How to return the remaining a line in a file after a specific string
How to return the remaining a line in a file after a specific string

Time:11-20

I have files that contain both strings and floats. I am interested in finding the floats after a specific string. Any help in writing such a function that reads the file look for that specific string and returns the float after it will be much appreciated.

Thanks

An example of a file is

aaaaaaaaaaaaaaa  bbbbbbbbbbbbbbb  cccccccccc
qq vvv rrr ssssa 22.6
zzzzx bbbb 12.0
xxxxxxxxxx 1.099
zzzz bbb nnn 33.5

In this specific example I am interested in getting the float after the string 'xxxxxxxxxx' and ignore the rest.

CodePudding user response:

You could read the entire file into a string and then use re.findall:

str_to_search = 'xxxxxxxxxx'

with open('input.txt', 'r') as file:
    lines = file.read()
    num = re.findall(r'^'   str_to_search   r' (\d (?:\.\d )?)', lines, flags=re.M)
    print(num)

CodePudding user response:

import re

lines = """Wire-BP-Frame, 1, -0.4
** Name: BC-4-Frame-LP-1 Type: Connector displacement
*Connector Motion, op=NEW
Wire-LP-Frame-1, 1, -1.835191406
** Name: BC-4-Frame-LP-2 Type: Connector displacement
*Connector Motion, op=NEW"""

str_to_search = 'Wire-LP-Frame-1, 1,'
num = re.findall(r'^'   str_to_search   r' (\d \.\d )', lines, flags=re.M)
print(num)
  • Related