You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中String.find()特殊用法及NMEA 0183 GGA消息统计优化

统计NMEA 0183格式中的$xxGGA类型消息

我有以下NMEA 0183格式的消息:

MNEAMessages = [
    "$GPGGA, 3555.1581, E, 1248.5819, W, 768.1, M",
    "$GLGGA, 3555.1581, E, 1248.5819, W, 768.1, M",
    "$GAGGA, 3555.1581, E, 1248.5819, W, 768.1, M",
    "$BDGGA, 3555.1581, E, 1248.5819, W, 768.1, M",
    "$GLRMC, 1, 2, 3, 4, 5, 6",
    "$GARMC, 1, 2, 3, 4, 5, 6"
]

我的目标是查找并统计其中符合$xxGGA格式的消息。目前我已经写出了实现该需求的代码:

counterGGA = 0
for message in MNEAMessages:
    startIndex = message.find("$")
    if startIndex != -1 and (message[startIndex + 3 : startIndex + 6] == "GGA"):
        # 没错,这是一条GGA消息
        counterGGA += 1

print(counterGGA) # 输出结果是4,符合预期

我想知道有没有更简洁高效的实现方式,比如类似下面这种写法:

if message.find("$xxGGA"):
    # 这才是更舒服的写法
    counterGGA += 1

最后我通过正则表达式找到了解决方案:

import re

match = re.search("\\$..GGA", message)
if match != None:
   counterGGA += 1 # 和find()方法一样,match.start()可以返回匹配的起始索引

内容的提问来源于stack exchange,提问作者emogo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 16:02:35