python中的匹配词

2024-04-19 10:53:20 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有一个关于在问题解决程序中查找单词的问题。如何添加一个组件,在输出答案之前检查问题的关键字?你知道吗

print ("Introduction Text")
print ("Explanation of how to answer questions")
Q1 = input ("Is your phone Android or Windows?")
if Q1 == "yes":
    print ("go to manufacturer")
if Q1 == "no":
    print ("next question")
Q2 = input ("Is your screen cracked or broken?")
if Q2 == "yes":
    print ("Replace Screen")
if Q1 == "no":
    print ("next question")
Q3 = input ("Does the handset volume turn up and down?") 
if Q1 == "no":
    print ("replace Hardware")
    print ("contact Manufacturer")
if Q1 == "yes":
    print ("next question")

Tags: ortono程序inputyourifis
1条回答
网友
1楼 · 发布于 2024-04-19 10:53:20

Pythonstrings有一些有用的方法,比如find,可以让您搜索字符串。还有regular expression库,它允许进行一些更复杂的字符串搜索。但是,您可以使用in执行子字符串搜索。以您的第一个问题为例,我们可以通过如下方式检查用户是否回答“是”,以及电话类型是否为“Android”:

>>> answer = input("Is your phone Android or Windows?")
Is your phone Android or Windows?"Yes android"
>>> if "yes" in answer.lower():
...     if "android" in answer.lower():
...             print "What android..."
... 
What android...

如果您有一个电话类型列表(Windows、Android),您可以循环查看该列表,并检查字符串中是否有any项,或者您可以使用列表理解,这使其非常简单:

>>> answer = input("Is your phone Android or Windows?")
Is your phone Android or Windows?"Yes, I've got a Windows and Android phone..."
>>> matching = [s for s in phone_types if s in answer.lower()]
>>> print matching
['windows', 'android']

你想添加什么,将取决于一些事情,比如你想搜索的列表等。因此,根据你实际需要,你可能想在你的问题中添加更多的信息。你知道吗

相关问题 更多 >