Конечно!Код ниже приведен для краткости:
def find_keywords(comment, word_list):
""":returns: List of matching keywords present in the comment, or the empty list"""
return [word for word in word_list if word.lower() in comment.body.lower()]
for comment in comment_stream:
if not should_be_ignored(comment):
found_kws = find_keywords(comment, keywords)
found_colors = find_keywords(comment, color_keywords)
if found_kws and found_colors:
# At this point, we're guaranteed to have *both* one or more keywords *and* one or more colors
send_message(comment, found_kws, found_colors)
Ключевым моментом здесь является следующее: вы создаете списки совпадений сначала , а затем после проверяете их, чтобы принять решениеесли вы хотите отправить сообщение.В этом случае, только если оба списка не пусты, вы перейдете к отправке сообщения.
(Реализация should_be_ignored()
и send_message()
, конечно, оставлена в качестве упражнениячитателю. :))
РЕДАКТИРОВАТЬ: Завершить реализацию исходного кода:
def send_message(comment, keywords, colors):
assert keywords and colors, "At this point, we should *only* be calling this function if we have at least one keyword and one color"
MSG_TEMPLATE = """Keyword *{keyword}* and color *{color}* detected
https://www.reddit.com{permalink}
```{comment_body}```"""
msg = MSG_TEMPLATE.format(
keyword=keywords[0],
color=colors[0],
permalink=comment.permalink,
comment_body=comment.body
)
slack_data = {'text': msg, 'mrkdwn': True,}
response = requests.post('https://hooks.slack.com/services/TB7AH6U2G/xxxxxxx/0KOjl9251TZExxxxxxxx',
data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
def should_be_ignored(comment, alerted):
return comment.id in alerted or (comment.author and comment.author.name in ignore_users)
def find_keywords(comment, word_list):
""":returns: List of matching keywords present in the comment, or the empty list"""
return [word for word in word_list if word.lower() in comment.body.lower()]
keywords = ['camera', 'nikon', 'canon']
color_keywords = ['blue', 'red']
with open(save_path, 'r') as fp:
alerted_comments = json.load(fp)
for comment in comment_stream:
if not should_be_ignored(comment, alerted_comments):
found_kws = find_keywords(comment, keywords)
found_colors = find_keywords(comment, color_keywords)
if found_kws and found_colors:
# At this point, we're guaranteed to have *both* one or more keywords *and* one or more colors
send_message(comment, found_kws, found_colors)
Обратите внимание, что все, что я сделал (за исключением нового требования, что у нас есть и (и цвет, и ключевое слово перед отправкой сообщения) предназначены для извлечения некоторой части вашей бизнес-логики в функции should_be_ignored()
и send_message()
, надеюсь, проясняя смысл основной части кода.Это должно быть заменой образца, с которого вы начали.