Python: Finding values after searching for a string in a text files

柔情痞子 提交于 2020-01-05 04:30:11

问题


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


回答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))



回答2:


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



回答3:


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.




回答4:


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)


来源:https://stackoverflow.com/questions/18714724/python-finding-values-after-searching-for-a-string-in-a-text-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!