Python:在文本文件中搜索字符串后查找值

2024-05-23 14:22:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,我正试图从多个文本文件中提取值。我可以用循环打开文件,但我正在寻找一种直接的方法来搜索字符串,然后返回字符串后的值。

我的结果文本文件如下

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 我希望能够搜索字符串,因为每个变量的位置可能会在以后更改。

很抱歉发布了这么简单的问题,只是似乎找不到一个直截了当的强有力的方法来找到它。

任何帮助都将不胜感激! 马特


Tags: 方法字符串minmeanmaxmmfcdegrees
3条回答

可以使用正则表达式查找名称和值:

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()

这样逐行读取文件,你就可以填一些字典了。

我的正则表达式使用值介于逗号之间的事实。

您可以使用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:将结果放入列表

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

我最喜欢的方法是测试行是否以所需文本开头:

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

然后使用逗号拆分行并返回值

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

相关问题 更多 >