简体   繁体   中英

how to get certain words from user input

Hello i am trying to make my program check for certain words in the user input. For example: The user types "add the numbers 6+6" what the programs does is it has a dictionary and checks the words in the dictionary and compares them to the words in the user input this example is "add". If the word add is in the user input then it checks for numbers and also math symbols this example is "6+6" then it outputs the answer?

I have tried:

if test == "add":
         do something

but this will not work unless the word "add" is all by itself. any help is very much appreciated.

You can loop through the input words and check them in your dictionary like

for word in input:
    if word in dic:
       pass

    fail

You can use the string.split() to split up the text into each word.

Then you can test each word individually for key words.

Details: http://docs.python.org/2/library/string.html

Look up the split method.

I'm pretty sure the split method by default returns a list of words split up by white space characters. So for example:

test_list = input.split()

test_list[1] should be 'add'

Best way to find out is to test it yourself, but I think it is something along those lines.

Cheers

It will work only in the cases like add 6+6 or 6+6 add or add <some_text> 6+6 etc.

   string = input()
    if 'add' in string:
        string = string.split('+')
        no1 = int(string[0].split()[-1])
        no2 = int(string[1].split()[0])
        print(no1 + no2)

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