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

Godot编写命令解析器:如何识别句中任意位置的关键词

实现方案

原有逻辑仅提取分词结果的第一个元素做匹配,因此只能识别句首命令。要支持任意位置关键词识别,直接遍历所有分词逐一匹配即可,修改后可直接运行的代码如下:

func process_command(_input: String) -> String:
    var words = _input.split(" ", false)
    if words.is_empty():
        return "Error: no words were parsed."

    for word in words:
        match word.to_lower():
            "hello":
                return hello()
            "help":
                return help()

    return "I don't understand."

func hello() -> String:
    return "Hello. How are you?"

func help() -> String:
    return "Press ESC for help."
注意事项
  • GDScript语法依赖缩进:hello()、help()两个函数需要和process_command()保持同级缩进,不能嵌套写在process_command内部,否则会触发语法报错。
  • 匹配前对单词做小写转换,可兼容任意大小写的输入形式,比如Hello、HELLO、hElLo都能正常触发对应响应。
  • 当前逻辑为匹配到第一个关键词就返回结果,如果需要支持单句触发多个命令,可调整遍历逻辑,收集所有命中的响应内容后统一返回。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 04:45:39