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

如何检测字符串中子串是否为独立单词(Python语音助手场景)

解决语音助手触发词误识别问题

我用Python开发语音助手,设置了“exit”“time”“quit”这类触发词,但语音识别经常误触发——比如识别到“sentimental”里的“time”就会播报时间,识别到“acquitted”里的“quit”就直接退出程序。我试过用单词边界符\b,但还要兼顾两种情况:独立的触发词(比如“quit”)和带修饰的情况(比如“please quit”)。

当前JSON配置

{
    "BasicOperations": {
        "goodbye": ["'bye", "exit", "quit", "see you"],
        "time": ["time ", "getting late"],
        "calculations": ["+", "-", "*", "/", "^"]
    }
}

当前检测代码

# Tell the time
if any(string in query for string in commands["time"]):
    engine.say('The time is ' + time)
    engine.runAndWait()

# Quit the program
elif any(string in query for string in commands["goodbye"]):
    engine.say("Good night sir! Have a nice sleep." if is_night else "Bye sir, have a great day!" )
    engine.runAndWait()
    exit()

elif any(string in query for string in commands["calculations"]):
    #op1, op2 = int(op1), int(op2)

    for op in commands["calculations"]:
        if (op in query):
            print(op)

    #answer =  get_operator_fn()(op1, op2)
    engine.say("Good night sir! Have a nice sleep." if is_night else "Bye sir, have a great day!" )
    engine.runAndWait()
    exit()

解决方案

核心是用正则表达式的单词边界匹配替代简单的子串判断,既能避免误识别内嵌子串,又支持触发词前后带修饰词的场景。

修改后的代码示例

import re

# 封装触发词匹配逻辑
def matches_trigger(query, triggers):
    for trigger in triggers:
        # 转义触发词中的特殊字符,构建单词边界匹配规则
        pattern = re.compile(rf'\b{re.escape(trigger)}\b', re.IGNORECASE)
        # 检查语句中是否存在独立的触发词
        if pattern.search(query):
            return True
    return False

# 播报时间
if matches_trigger(query, commands["time"]):
    engine.say(f'The time is {time}')
    engine.runAndWait()

# 退出程序
elif matches_trigger(query, commands["goodbye"]):
    engine.say("Good night sir! Have a nice sleep." if is_night else "Bye sir, have a great day!" )
    engine.runAndWait()
    exit()

# 计算操作(保留原有逻辑,运算符无单词边界问题)
elif any(op in query for op in commands["calculations"]):
    for op in commands["calculations"]:
        if op in query:
            print(op)
    engine.say("Good night sir! Have a nice sleep." if is_night else "Bye sir, have a great day!" )
    engine.runAndWait()
    exit()

关键说明

  • re.escape(trigger):处理触发词中的特殊字符(比如'bye里的单引号),避免破坏正则结构
  • \b:确保触发词是独立单词,不会匹配其他单词的内嵌子串(比如“sentimental”里的“time”)
  • re.IGNORECASE:忽略大小写,适配语音识别的大小写误差(比如识别成“Time”也能触发)
  • 对于“see you”“getting late”这类短语,\b会匹配整个连续短语,只要短语在语句中是独立的语义单元

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:03:29