我有一个大的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中可以完成的吗?在
这可以通过逐字手动读取文件或使用python的正则表达式来实现。在我看来,使用正则表达式可以在不损失可读性的情况下使代码更简洁,所以我将重点讨论这个解决方案。在
从到
re
模块(https://docs.python.org/3/library/re.html)的python文档:在您的示例中,您希望在每次出现“Temperature”之后搜索任意数量的数字
\d+
,可选的是一个文本小数点\.?
和更多的数字\d+?
。re.findall()
函数可能很有用。在可以使用正则表达式组匹配
我讨厌正则表达式,所以这里是纯python解决方案。在
相关问题 更多 >
编程相关推荐