在python中,如何让用户按照某种形式输入命令?
很抱歉这个血腥的标题,我想不出它叫什么。在python中,如何让用户按照某种形式输入命令?,python,search,input,command,detect,Python,Search,Input,Command,Detect,很抱歉这个血腥的标题,我想不出它叫什么。 基本上,我想问用户“您想做什么?”并让他们能够执行许多命令。例如,他们会说“搜索福克斯”,这个程序就可以了 if any(search in i for i in list): print(list[search]) else: print(search + " not found.") 因此,基本上,我如何让代码检测“Search for[x]”格式并将x分配给变量Search。此外,如果有一个名字,这将被称为什么?我想这将有助于我下
基本上,我想问用户“您想做什么?”并让他们能够执行许多命令。例如,他们会说“搜索福克斯”,这个程序就可以了
if any(search in i for i in list):
print(list[search])
else:
print(search + " not found.")
因此,基本上,我如何让代码检测“Search for[x]”格式并将x分配给变量Search。此外,如果有一个名字,这将被称为什么?我想这将有助于我下次搜索它。下面的代码通过从用户提供的输入中删除命令(此处为搜索)来查找关键字,这样搜索查询就被分离了
def search(search_word):
# your search function here
pass
# get input from the user
user_input = raw_input("What would you like to do? ").lower()
# make the code easier to reuse
search_command = "search for"
if len(user_input) > 0:
if user_input.startswith(search_command):
# use slices to remove the first part of the input, and then remove all whitepsace
search_word = user_input[len(search_command):].strip()
search(search_word)
Search
是命令还是Search for fox
是命令?您描述的是解析输入以提取命令。在最简单的形式中,您可以只执行if user\u input.lower().startswith(“search for”):
。更复杂的版本可能涉及正则表达式或其他解析技术。@padraiccanningham搜索将是命令。@jornsharpe是的,这就是我的意思,谢谢。然后,我将如何提取“搜索”后的位并将其分配给变量?@CharlieDeBeadle对于简单版本,从查看各种开始。谢谢,这就是我最后所做的。