简体   繁体   中英

matching words in python

Hi I have a question here about finding words in a trouble shooting question program. How can I add a component which will check the questions for key words before outputting the answers?

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")

Python strings have some useful methods like find that will let you search for strings. There's also the regular expression library that will allow for some more complex string searches. What you can do however, is us in to perform a sub-string search. Taking you first question as an example, we can check that the user answered "yes", and whether or not the phone type is "Android" by using something like the following:

>>> 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...

If you've got a list of phone types (Windows, Android) you can loop over that list, and check whether or not any of the items are present in your string, or you can use list comprehension which makes it quite simple:

>>> 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']

What you want to add, will depending on a few things like the list(s) you want to search against etc. So, depending on what you actually need you might want to add some more information to your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM