Python:在文本文件中搜索字符串后查找值 [英] Python: Finding values after searching for a string in a text files
问题描述
我是 Python 世界的新手,我正在尝试从多个文本文件中提取值.我可以用循环打开文件,但我正在寻找一种直接的方法来搜索字符串,然后在它之后返回值.
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
所以我希望能够搜索说Max Tsai-Wu =",它返回 0.6850我希望能够搜索字符串,因为每个变量的位置在以后可能会发生变化.
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
推荐答案
你可以使用正则表达式:
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)
印刷品:
0.6850
UPD:将结果放入列表
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))
这篇关于Python:在文本文件中搜索字符串后查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!