简体   繁体   English

检查列表中至少一个关键字实例

[英]Checking for at least one instance of keyword in list

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. 我正在Python中使用Clarifai的API从照片中获取概念名称,并想确定其中是否与局部变量匹配。 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" . 我的局部变量是定义为"car"keyword I tried running if keyword in concept['name'] , but my console listed 11 False s before a True . 我尝试if keyword in concept['name']运行if keyword in concept['name'] ,但是我的控制台在True之前列出了11 False Effectively, I'd like to make a function that does something if there is at least one instance of keyword in concept['name'] . 实际上,我想创建一个函数,如果在concept['name']中至少有一个keyword实例,该函数可以执行某些操作。 If anyone would chime in, I would much appreciate the help. 如果有人愿意,我将非常感谢您的帮助。

You can use any operator to check you keyword appears in any of the list memnber concept['name'] 您可以使用任何运算符来检查keyword出现在列表成员concept['name']任何一个中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: 但是,它仅适用于列表元素不以\\n结尾的情况,以删除所有\\n使用必须对列表进行预处理的方式,如下所示:

>>> clean_list = list(map(lambda s: s.strip(), concept['name']))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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