-1

I am working on a text-based game, and want the program to search for multiple specific words in order in the user's answer. For example, I wan't to find the words "Take" and "item" in a user's response without making the user type specifically "Take item".

I know that you can use

    if this in that

to check if this word is in that string, but what about multiple words with fluff in between?

The code I am using now is

if ("word1" and "word2" and "word3) in ans:

but this is lengthy and won't work for every single input in a text-based game. What else works?

  • 1
    Possible duplicate of [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Austin Jun 06 '19 at 02:48

2 Answers2

1

A regex based solution might be to use re.match:

input = "word1 and word2 and word3"
match = re.match(r'(?=.*\bword1\b)(?=.*\bword2\b)(?=.*\bword3\b).*', input)
if match:
    print("MATCH")

The regex pattern used makes use of positive lookaheds which assert that each word appears in the string.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

We might here want to design a library with keys and values, then look up for our desired outputs, if I understand the problem correctly:

word_action_library={
   'Word1':'Take item for WORD1',
   'Some other words we wish before Word1':'Do not take item for WORD1',
   'Before that some WOrd1 and then some other words':'Take items or do not take item, if you wish for WORD1',

   'Word2':'Take item for WORD2',
   'Some other words we wish before Word2':'Do not take item for WORD2',
   'Before that some WOrd2 and then some other words':'Take items or do not take item, if you wish for WORD2',

   }

print list(value for key,value in word_action_library.iteritems() if 'word1' in key.lower())
print list(value for key,value in word_action_library.iteritems() if 'word2' in key.lower())

Output

['Take items or do not take item, if you wish for WORD1', 'Do not take item for WORD1', 'Take item for WORD1']
['Take items or do not take item, if you wish for WORD2', 'Do not take item for WORD2', 'Take item for WORD2']
Emma
  • 27,428
  • 11
  • 44
  • 69