在python文件中定位字符串的位置

2024-09-28 18:55:07 发布

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

我有一个大的txt文件,我想在其中找到一组特定的字符串并提取紧随其后的数字。例如:

26.08.15 14:52:04 Pressure 1.02 Temperature 32.5 NOb 10993 VB 28772  
.... <other stuff>
26.08.15 14:53:06 Pressure 1.03 Temperature 31.6 NOb 10993 VB 28008 
.... <other stuff>

等等

我希望能够找到String=Temperature并提取下面的数值。我见过一些例子,告诉我字符串是否存在,但没有告诉我它在哪里,或者如何索引它后面的信息。这是Python中可以完成的吗?在


Tags: 文件字符串txt信息string数字例子数值
3条回答

这可以通过逐字手动读取文件或使用python的正则表达式来实现。在我看来,使用正则表达式可以在不损失可读性的情况下使代码更简洁,所以我将重点讨论这个解决方案。在

从到re模块(https://docs.python.org/3/library/re.html)的python文档:

(?<=...) Matches if the current position in the string is preceded by a match for ... that ends at the current position.

This example looks for a word following a hyphen:

m = re.search('(?<=-)\w+', 'spam-egg')
m.group(0)

在您的示例中,您希望在每次出现“Temperature”之后搜索任意数量的数字\d+,可选的是一个文本小数点\.?和更多的数字\d+?re.findall()函数可能很有用。在

可以使用正则表达式组匹配

import re
with open("example.txt") as f:
    for line in f:
        m = re.match(".* Temperature (.*?) .*", line)
        if m:
            try:
                number = float(m.group(1))
                print(number)
            except ValueError:
                pass # could print an error here because a number wasn't found in the expected place

我讨厌正则表达式,所以这里是纯python解决方案。在

lines = "26.08.15 14:52:04 Pressure 1.02 Temperature 32.5 NOb 10993 VB 28772 .... 26.08.15 14:53:06 Pressure 1.03 Temperature 31.6 NOb 10993 VB 28008 ...."
lines = lines.split()
for n, word in enumerate(lines):  
    if word in ['Temperature', 'Pressure']:
        print(word, lines[n+1]) 

相关问题 更多 >