首页 > 解决方案 > 如何从 Python 语音识别中提取子字符串

问题描述

我正在尝试从用户所说的内容中提取字符串;但是,我在使用 -re 时遇到了当前解决方案的问题。

我首先尝试创建一个虚拟助手来查找有关用户请求的信息,例如电影。而不是必须第二次运行语音识别来创建一个变量,我想从原始输入中提取它。这就是我的意思:

if "about the movie" in command:
    about_the_movie(command)

def about_the_movie(command):
    m = re.match(r'(.*) about the movie (.*)', command)
    movie = m.group(2)
    movie.replace(" ", "+")
    url = ('http://www.omdbapi.com/?t=' + movie + '&apikey=********')
    r = requests.get(url).json()

我现在遇到的问题是,如果用户说“关于电影‘黑暗骑士’,它会抛出一个AttributeError: 'NoneType' object has no attribute 'group'. 我理解这是因为那时 m.group(2) 不存在,但我我不确定我能做些什么来解决这个问题。

我还想添加查找单词定义的功能,但是如果用户说“汽车的定义”与“汽车的定义是什么”,则会遇到同样的问题

谢谢!

标签: pythonstringinputsubstringspeech-recognition

解决方案


所以我一直在搞砸这个并意识到如果有空格它会抛出那个错误:

m = re.match(r'(.*) about the movie (.*)', command)

对比

m = re.match(r'(.*)about the movie (.*)', command)

我很感激你的回应!


推荐阅读