1

I'm new to the world of python and I'm trying to extract values from multiple text files. I can open up the files fine with a loop, but I'm looking for a straight forward way to search for a string and then return the value after it.

My results text files look like this

SUMMARY OF RESULTS
Max tip rotation =,-18.1921,degrees
Min tip rotation =,-0.3258,degrees
Mean tip rotation =,-7.4164,degrees
Max tip displacement =,6.9956,mm
Min tip displacement =,0.7467,mm
Mean tip displacement = ,2.4321,mm
Max Tsai-Wu FC =,0.6850
Max Tsai-Hill FC =,0.6877

So I want to be able to search for say 'Max Tsai-Wu =,' and it return 0.6850 I want to be able to search for the string as the position of each variable might change at a later date.

Sorry for posting such an easy question, just can't seem to find a straight forward robust way of finding it.

Any help would be greatly appreciated! Matt

user2739143
  • 591
  • 2
  • 8
  • 13

4 Answers4

1

You can make use of regex:

import re


regexp = re.compile(r'Max Tsai-Wu.*?([0-9.-]+)')
with open('input.txt') as f:
    for line in f:
        match = regexp.match(line)
        if match:
            print match.group(1)

prints:

0.6850

UPD: getting results into the list

import re


regexp = re.compile(r'Max Tsai-Wu.*?([0-9.-]+)') 
result = []
with open('input.txt') as f:
    for line in f:
        match = regexp.match(line)
        if match:
            result.append(match.group(1))
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Thank you so much! Could I just ask what does the r before the Max Tsai-Wu do? Also the .*?([0-9.-]+)? – user2739143 Sep 10 '13 at 09:56
  • @user2739143, sure, `r` means it's just a [raw string](http://stackoverflow.com/questions/4415259/python-raw-strings). `.*?([0-9.-]+)`: `.*?` here means non-greedy match for any set of characters - in this case it will match anything between `Max Tsai-Wu` and your float number, `([0-9.-]+)` is a capturing group for the float number you want to extract. – alecxe Sep 10 '13 at 09:58
  • Can I just ask one more question! Say I want to create a list of all the values taken from that loop, how would I make a list with all the values, i.e. something like this listOfMaxTipRotation = listOfMaxTipRotation , maxTipRotation – user2739143 Sep 10 '13 at 10:33
  • Sorry to keep bothering you just got another quick question. I'm trying to export the data obtained to a CSV file, but when I export it, the lists still have the [] either side of the lists. How do I get rid of them? Also each value has '' either side, how do I remove them? Thank you! – user2739143 Sep 10 '13 at 12:25
  • I have one text file on many lines of contact names separated with their phone numbers by comma. I need to search for the matching contact name when the user inputs and displays the relevant phone number. How to associate this script with React Native android app? – Himagaran Jun 01 '21 at 06:57
1

My favorite way is to test if the line starts with the desired text:

keyword = 'Max Tsai-Wu' 
if line.startswith(keyword):

And then split the line using the commas and return the value

try:
    return float(line.split(',')[1])
except ValueError:
    # treat the error
asafpr
  • 347
  • 1
  • 5
0

You can use regular expression to find both name and value:

import re

RE_VALUE = re.compile('(.*?)\s*=,(.*?),')

def test():
    line = 'Max tip rotation =,-18.1921,degrees'
    rx = RE_VALUE.search(line)
    if rx:
        print('[%s] value: [%s]' % (rx.group(1), rx.group(2)))


test()

This way reading file line by line you can fill some dictionary.

My regex uses fact that value is between commas.

Michał Niklas
  • 53,067
  • 18
  • 70
  • 114
0

If the files aren't that big, you could simply do:

import re
files = [list, of, files]
for f in files:
    with open(f) as myfile:
        print re.search(r'Max Tsai-Wu.*?=,(.+)', myfile.read()).group(1)
TerryA
  • 58,805
  • 11
  • 114
  • 143