Python:检查字典项是否在字符串中,然后返回匹配项

2024-04-25 19:33:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据库表,如下所示:

id    phrases                    message
1     "social media, marketing"  "This person is in marketing!"
2     "finance, fintech          "This person is in finance!"

我把关键短语循环了一遍,然后把它们添加到词典中,如下所示:

^{pr2}$

然后产生以下结果:

# phrase_list
{'social media': 'This person is in marketing!', 
 'marketing': 'This person is in marketing!', 
 'finance': 'This person is in finance!', 
 'fintech': 'This person is in finance!'}

所以,每一个短语都有它自己的伴随信息,在其他地方使用。在

现在,我可以将dict键与字符串进行比较,如下所示:

descriptions = ["I am in marketing, and it is super awesome", "I am in finance, and it is super awesome"]

我的下一步是将该字符串与键进行比较,如果它包含任何关键字,则打印匹配的键及其值/消息。到目前为止,我得到的是:

for description in descriptions:
    print(description)
    if has_message == True:
        if any(x in description for x in phrase_list):
            # print matching keyword and message
        else:
            print("No matches, but a phrase list exists")

所以我的问题是,我需要用什么来替换这个注释来输出1)它匹配的关键字,2)与该关键字关联的消息?在


Tags: andinmessageissocial关键字descriptionthis
2条回答

你只需要重新构造你的代码。对它的需求来自于使用any,它不返回x使表达式的计算结果为True的信息。它只是告诉你,有人做过,或者没有人做过。如果你真的关心你必须循环使用哪一个或者可能使用next。总之,有一种方法可以做到:

for description in descriptions:
    print(description)
    if has_message == True:
        for x in phrase_list:
            if x in description:
                print(x, phrase_list[x])
                break
        else:
            print("No matches, but a phrase list exists")

注:

如果for上的else令人困惑,只需将其删除。只有当x不在任何描述中时,代码才会到达它。在

可能需要稍微调整一下,但可以使用正则表达式搜索匹配的键,然后在字典中查找,例如:

import re

phrase_list = {'social media': 'This person is in marketing!', 
 'marketing': 'This person is in marketing!', 
 'finance': 'This person is in finance!', 
 'fintech': 'This person is in finance!'}

descriptions = ["I am in marketing, and it is super awesome", "I am in finance, and it is super awesome", 'john smith']

def find_department(lookup, text):
    m = re.search('|'.join(sorted(lookup, key=len, reverse=True)), text)
    if m:
        return lookup[m.group(0)]
    else:
        return 'This person is a mystery!'

然后运行这个程序可以:

^{pr2}$

相关问题 更多 >