Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python to finding a string in a file and extracting the integer value on the same line

I'm new to python and having the following issue.

I have a text file (filename.dat) which provides information about my model. A summary of the relevant portions are as follows:

      NUMBER OF ELEMENTS IS                               1367466
      NUMBER OF NODES IS                                   252624
      NUMBER OF NODES DEFINED BY THE USER                  248291
      NUMBER OF INTERNAL NODES GENERATED BY THE PROGRAM      4333
      TOTAL NUMBER OF VARIABLES IN THE MODEL               783873

I can search for the line using the following python commands:

with open('filename.dat', 'r') as inF:
    for line in inF:
        if 'NUMBER OF ELEMENTS IS' in line:
            print "true"

However I'm not sure how to extract the integer value (1367466) on the same line as 'NUMBER OF ELEMENTS IS'. Does anyone now how to extract the string numbers from a line that is mixed with string characters?

like image 904
Paul M Avatar asked Jun 07 '26 03:06

Paul M


1 Answers

Split the line by whitespace from the right, once:

In [18]: line.rsplit(None, 1)
Out[18]: ['TOTAL NUMBER OF VARIABLES IN THE MODEL', '783873']

Take the second part:

In [19]: line.rsplit(None, 1)[1]
Out[19]: '783873'

Convert it to int:

In [20]: int(line.rsplit(None, 1)[1])
Out[20]: 783873

You can use tuple unpacking to make the code cleaner (if your entire file is of this format):

with open('filename.dat', 'r') as inF:
    for line in inF:
        label, number = line.rsplit(None, 1)
        if 'NUMBER OF ELEMENTS IS' in label:
            print "true"
            number = int(number)
            ...

If some lines are of a different format, you'll have to search first and split later:

with open('filename.dat', 'r') as inF:
    for line in inF:
        if 'NUMBER OF ELEMENTS IS' in line:
            print "true"
            label, number = line.rsplit(None, 1)   # label is unused then
            number = int(number)
            ...
like image 194
Pavel Anossov Avatar answered Jun 08 '26 15:06

Pavel Anossov