实施例
from somelib import Punch, Kick, Throw, Dropkick, Uppercut
globals()[class_name](x, y)
line = getline("Attacks.txt", count)
line = line.rstrip()
linelist = line.split()
class_name = linelist[1]
value = linelist[2]
class_object = globals()[class_name]
item = class_object(value)
# or shortly in one line:
# item = globals()[linelist[1]](linelist[2])
我想检查my_list上的任何字词是否在描述中,如果是,请不要做任何事情。如果my_list不在说明中,我想返回字符串'未找到的关键字'。
我将如何编写此代码?
答案 0 :(得分:3)
您可以将all
与双列表理解结合使用:
description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel']
my_list = ['travel','fire']
def response():
return "found" if any(i in b for i in my_list for b in description) else "Keywords not found"
答案 1 :(得分:1)
保存集合中的单词并检查my_list
中的单词是否在集合中。当my_list
中没有短语时,此仅有效。即my_list
中的所有单词都是单字组。
description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel']
my_list = ['travel','fire']
set_words_in_description = set()
for s in description:
# add new words in set_words_in_description
set_words_in_description.update(set(w for w in s.split()))
使用isdisjoint
def find_word_method_disjoint(my_list, set_words_in_description):
# check if my_list is disjoint with set_wrods_in_description
return not set_words_in_description.isdisjoint(my_list)
%timeit find_word_method_disjoint(my_list, set_words_in_description)
189 ns ± 1.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit response() # function given by the accepted answer.
572 ns ± 9.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
答案 2 :(得分:0)
您可以使用re.findall()
从description
中的句子中提取所有单词,并检查其中是否存在my_list
中的任何单词:
import re
def find_words(words, text):
desc_words = re.findall(r'[^\s,.]+', "".join(text))
for word in words:
if word in desc_words:
return "found"
return "Keywords not found"
哪个输出:
>>> description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel']
>>> my_list = ['travel','fire']
>>> find_words(my_list, description)
found
或者您可以使用此set()
方法:
def find_words(words, text):
return "found" if set(words).intersection(re.findall(r'[^\s,.]+', "".join(text))) else "Keywords not found"
注意:如果您遇到,.
以外的不同标点符号的句子,则必须更新正则表达式。
答案 3 :(得分:0)
你可以尝试设置这样的东西吗?
description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel']
my_list = ['travel','fire']
flat=[k for i in description for k in i.split()]
print(any({i}.issubset(set(flat))for i in my_list))
输出:
True