我有两个列表:
Keyword = ['Dog', 'Cat', 'White Cat', 'Lion', 'Black Cat']
Definition = ['Mans Best Friend', 'The cat is a domestic species of a small carnivorous mammal', 'White cats are cute', 'Lions are Carnivores Wild Animal', 'Black Cats are Black in color']
我正在从以下命令获得"查询"中的语音输入:
import speech_recognition as sr
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language ='en-in')
print(f"User said: {query}n")
except Exception as e:
print(e)
print("Unable to Recognize your voice.")
return "None"
return query
query = takeCommand().Capitalize()
现在,如果查询中包含Dog,我想从列表中打印相应的定义,即"Man's Best Friend",如果查询包含Cat,我想向用户显示有多个关键字中包含"Cat",即"Cat"、"White Cat"、《Black Cat》,如果查询内的单词不在列表中,我想打印";找不到关键字,请检查您的关键字">
有人知道如何解决这个问题吗?
不同情况下的输入输出:
输入:查询中有"Dog"。程序应该检查是否有一个以上的单词中有Dog。如果是,它应该打印所有包含Dog的关键字,如果否,则应该打印相应的定义。在Keywords的情况下,Dog的输出应该是相应的定义,即"Mans Best Friend"。
输入:查询中有"Cat"。在这种情况下,有3个关键字中有Cat,即"Cat"、"Black Cat"one_answers"White Cat"。因此,在这里,代码应该打印这些关键字,而不是它们的定义。所以这个案例的输出:我们发现了多个关键词:"猫","黑猫",‘白猫’
输入:查询中有"Panther"。Keywords中没有Panther,所以它应该打印";没有匹配关键字";。
Keyword = ['Dog', 'Cat', 'White Cat', 'Lion', 'Black Cat']
Definition = ['Mans Best Friend', 'The cat is a domestic species of a small carnivorous mammal', 'White cats are cute', 'Lions are Carnivores Wild Animal', 'Black Cats are Black in color']
def take_cmd(cmd):
multiple_val=[]
if cmd in Keyword:
for i,j in enumerate(Keyword):
if cmd in j:
multiple_val.append((i,j))
if len(multiple_val)>1:
i_removed=[j for i in multiple_val for j in i if type(j)!=int]
print(f"We have found multiple keywords : {i_removed}")
else:
print(Definition[Keyword.index(cmd)])
else:
print("There are no Matching Keywords")
这个代码的作用是:
- 检查输入的值是否存在于
Keyword
中,如果不存在,则返回"0";没有匹配关键字"> - 如果该值存在,则将检查是否存在多个实例,或者该值是否在多个索引中可用
- 如果这也返回true,则它将其附加到
multiple_vals
。如果multiple_val
的长度大于1,则仅其将显示f"We have found multiple keywords : {i_removed}"
- 否则在CCD_ 5中显示相应的索引