gpt4 book ai didi

python - 编写脚本以使用正则表达式在两个模式之间打印字符串,但仅最后一次出现

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:16 28 4
gpt4 key购买 nike

我正在我的 Raspberry Pi 3 上编写一个 python 脚本,它将记录来自开源秤的重量并将它们放入数据库中。秤只是将输出/读数记录到一个文件中。问题是秤输出了很多我不需要的数据。每次脚本运行时,它都会在文件底部添加一个新的读数,您可以在下面看到它的一部分。所以基本上我需要的是最新的体重读数,它总是在文件的最后一行。

我不太擅长正则表达式。尽管我进行了搜索和尝试,但我似乎无法仅分离出最后的体重读数。

Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 791
Press x to bring up settings
Readings:
1274,2.5007,lbs,540611,

Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 792
Press x to bring up settings
Readings:
1341,2.5008,lbs,540620,

Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 792
Press x to bring up settings
Readings:
1321,2.5009,lbs,540643,

最后一行: 1321,2.5009,磅,540643,

我需要“2.5009”所在的值,但我不能简单地匹配该数字,因为它会随着每次添加的读数而发生巨大变化,最后一行的其他数字也是如此。唯一保持不变的是逗号和“lbs”。

最佳答案

也许,这个表达式可能会提取最后一个值:

.*Readings:\s*[^,]*,\s*([^,]*?)\s*,

测试

import re

regex = r".*Readings:\s*[^,]*,\s*([^,]*?)\s*,"

test_str = """
Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 791
Press x to bring up settings
Readings:
1274,2.5007,lbs,540611,

Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 792
Press x to bring up settings
Readings:
1341,2.5008 ,lbs,540620,

Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 792
Press x to bring up settings
Readings:
1321, 2.5009,lbs,540643,

"""

print(re.findall(regex, test_str, re.DOTALL))

输出

['2.5009']

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


关于python - 编写脚本以使用正则表达式在两个模式之间打印字符串,但仅最后一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57651883/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com