我试图从用户所说的内容中提取出一条线索;但是,我当前使用 - 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) 不存在,但我不确定我可以采取什么解决方法。
我还想添加查找单词定义的功能,但如果用户说“汽车的定义”与“汽车的定义是什么”,则会遇到同样的问题
谢谢!
最佳答案
如果您的字符串包含引号,则:
>> m = re.match(r"about the movie .(.*).", "about the movie 'The Dark Knight'")
>> print(m.group(1))
The Dark Knight
关于python - 如何从 Python 语音识别中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54192430/