2

I'm using Clarifai's API in Python to get concept names from a photo and would like to determine if any of them match a local variable. The following command invokes a list:

In [1]:  p1_response = model.predict_by_filename(filename='PATH_TO_FILE')
         p1_concepts = p1_response['outputs'][0]['data']['concepts']
         for concept in p1_concepts:
         print(concept['name'])
Out [2]: street
         outdoors
         architecture
         travel
         city
         horizontal plane
         pavement
         road
         house
         town
         urban
         car
         no person
         building
         stock
         luxury
         traffic
         apartment
         business
         tourism

My local variable is a keyword defined as "car". I tried running if keyword in concept['name'], but my console listed 11 Falses before a True. Effectively, I'd like to make a function that does something if there is at least one instance of keyword in concept['name']. If anyone would chime in, I would much appreciate the help.

solo
  • 743
  • 2
  • 6
  • 17

1 Answers1

3

You can use any operator to check you keyword appears in any of the list memnber concept['name']

>>> keyword = "car"
>>> concept['name'] = ['car', 'carr', 'carrrr']
>>> any(word == keyword for word in concept['name'])
>>> True

However it is only applicable to list elements if they are not ending with \n to remove all \n use have to preprocess the list as follows:

>>> clean_list = list(map(lambda s: s.strip(), concept['name']))
Sohaib Farooqi
  • 5,457
  • 4
  • 31
  • 43
  • Hmm. I preprocessed the list before using the any operator, and then ran an if-then statement to return True if any of the elements had the same value as the keyword, but I got the same output as before: 11 Falses before a True. How could I get the console to return True without the other False stamens if at least one instance of keyword exists in the list? – solo Dec 15 '17 at 15:32
  • Its not possible unless your keyword is `list`. Can you post your exact solution so that I can check – Sohaib Farooqi Dec 15 '17 at 15:36
  • 1
    Ok. I did a while statement that does something before breaking, which works for now. I was trying the following before: `clean_list = list(map(lambda s: s.strip(), concept['name']))`, `if any(word == keyword for word in concept['name']):`, `print(True)`, `else:`, `print(False)`. – solo Dec 15 '17 at 15:45