我有一个数据库表,如下所示:
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)与该关键字关联的消息?在
你只需要重新构造你的代码。对它的需求来自于使用
any
,它不返回x
使表达式的计算结果为True
的信息。它只是告诉你,有人做过,或者没有人做过。如果你真的关心你必须循环使用哪一个或者可能使用next
。总之,有一种方法可以做到:注:
如果
for
上的else
令人困惑,只需将其删除。只有当x不在任何描述中时,代码才会到达它。在可能需要稍微调整一下,但可以使用正则表达式搜索匹配的键,然后在字典中查找,例如:
然后运行这个程序可以:
^{pr2}$相关问题 更多 >
编程相关推荐