首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python -可能只在两个关键字列表中检测到关键字时才发送消息?

Python -可能只在两个关键字列表中检测到关键字时才发送消息?
EN

Stack Overflow用户
提问于 2018-11-24 01:40:22
回答 1查看 127关注 0票数 1

我有一个python脚本,它从关键字列表keywords = ['camera', 'nikon']中检测一个关键字,然后发送一条消息给Slack,如下所示

关键词摄像机检测到

‘'Reddit帖子网址’

“包含关键字的'reddit注释”

如果脚本从第二个关键字列表color_keywords = ['red', 'blue']中检测到一个关键字,那么它将发布以下内容

关键词摄像机检测到

‘'Reddit帖子网址’

“包含关键字的'reddit注释”

颜色被检测到

我的问题是,我是否能够得到脚本,所以只有在找到每个关键字列表中的关键字时,它才会发送消息?因此,如果它只从第一个列表中找到一个关键字,它将被忽略,如果它从第二个列表中找到一个关键字,它也将被忽略。但是,如果它从这两个列表中都找到了一个关键字,它就会将消息发送到slack。

下面是我的当前代码

代码语言:javascript
复制
MSG_TEMPLATE = """Keyword *{keyword}* detected
https://www.reddit.com{permalink}
```{comment_body}```"""

关键词=‘照相机’,‘尼康’,‘佳能’

color_keywords =‘蓝色’,‘红色’

使用open(save_path,'r')作为fp:

代码语言:javascript
复制
alerted_comments = json.load(fp)
代码语言:javascript
复制
for comment in comment_stream:
代码语言:javascript
复制
    if comment.id in alerted_comments:
代码语言:javascript
复制
        continue
代码语言:javascript
复制
    if comment.author:  # if comment author hasn't deleted
代码语言:javascript
复制
        if comment.author.name in ignore_users:
代码语言:javascript
复制
            continue
代码语言:javascript
复制
    if any(kw.lower() in comment.body.lower() for kw in keywords):
代码语言:javascript
复制
        found_kws = [kw for kw in keywords if kw.lower() in comment.body.lower()]
代码语言:javascript
复制
        msg = MSG_TEMPLATE.format(
代码语言:javascript
复制
            keyword=found_kws[0],
代码语言:javascript
复制
            permalink=comment.permalink,
代码语言:javascript
复制
            comment_body=comment.body
代码语言:javascript
复制
        )
代码语言:javascript
复制
        if any(kw.lower() in comment.body.lower() for kw in color_keywords):
代码语言:javascript
复制
            msg += "\n<!here> *A color was detected*"
代码语言:javascript
复制
        slack_data = {'text': msg, 'mrkdwn': True,}
代码语言:javascript
复制
        response = requests.post('https://hooks.slack.com/services/TB7AH6U2G/xxxxxxx/0KOjl9251TZExxxxxxxx',
代码语言:javascript
复制
                                         data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
代码语言:javascript
复制

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

发布于 2018-11-24 02:03:05

好的!为了简洁起见,下面的代码摘录如下:

代码语言:javascript
复制
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()的实现是留给读者的练习。*)

编辑:完成原始代码的实现:

代码语言:javascript
复制
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()函数中,希望能够澄清代码主体的意图。这应该是您开始使用的示例的插入替代。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53454472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档