语音识别计算器求值异常求助:乘号、百分比及括号兼容问题
解决方案:语音识别计算器的求值与功能扩展问题
核心问题处理逻辑
针对你遇到的三个问题,我们需要在将识别文本传入eval()前,先对内容做标准化转换,同时增加错误防护:
1. 乘号替换(X→*)
语音识别输出的X/x不是JavaScript合法乘号,直接替换为*即可让eval()识别。
2. 百分比功能支持
处理两种常见的百分比语音表述:
- 单独百分比:
N percent→ 转换为N/100 - 比例表述:
N percent of M→ 转换为M*(N/100)
3. 括号语音转换
将语音中的括号描述(如open bracket、close parenthesis)转换为对应的符号(和)。
4. 错误防护
用try-catch包裹求值逻辑,避免识别内容非法时页面崩溃。
修改后的完整代码
function speechRecognition() { const recognition = new webkitSpeechRecognition(); recognition.lang = "en-US"; recognition.onstart = function () { microphone.classList.add(`listening`); }; recognition.onspeechend = function () { microphone.classList.remove(`listening`); recognition.stop(); }; recognition.onresult = function (event) { console.log(event); let transcript = event.results[0][0].transcript; // 标准化识别文本为合法JS表达式 const processedTranscript = transcript // 替换乘号 .replace(/[xX]/g, '*') // 转换括号语音表述 .replace(/open bracket|open parenthesis/g, '(') .replace(/close bracket|close parenthesis/g, ')') // 处理"X percent of Y"结构 .replace(/(\d+(?:\.\d+)?) percent of (\d+(?:\.\d+)?)/gi, '$2*($1/100)') // 处理单独百分比 .replace(/(\d+(?:\.\d+)?) percent/gi, '$1/100'); try { let result = eval(processedTranscript); displayOutput.innerHTML = cleanOutput(result); } catch (error) { displayOutput.innerHTML = 'Invalid expression'; console.error('Evaluation error:', error); } }; recognition.start(); }
测试场景验证
- 说出
five times three→ 识别为5 X 3→ 处理后5*3→ 输出15 - 说出
twenty percent→ 处理为20/100→ 输出0.2 - 说出
five percent of hundred→ 处理为100*(5/100)→ 输出5 - 说出
open bracket five plus three close bracket times two→ 处理为(5+3)*2→ 输出16
注意:
eval()存在安全风险,若面向公开用户使用,建议替换为更安全的表达式解析库(如math.js),个人使用场景下可直接采用上述方案。
内容的提问来源于stack exchange,提问作者mariam
相关产品推荐
相关产品推荐

