首页 > 解决方案 > 检查数据库中的句子是否包含字典中的某些单词

问题描述

我有一个巨大的字典(在 Python 中),其中包含数百万个单词,每个单词都有一个分数,表示受欢迎程度。(注意:我将它作为字典,但我也可以轻松地将它作为数据框使用)。我还有一个包含几百个句子的数据库/SQL 表,每个句子都有一个 ID。

我想看看每个句子是否包含一个流行词,即它是否包含一个分数低于某个数字n的词。遍历每个句子并且每次检查每个单词以查看它是否在字典中以及它的分数是低效的吗?

还有其他更有效的方法吗?

标签: pythondatabasedictionary

解决方案


这是您可以采用的方法:我的示例代码中的“6”是您在问题中添加的“n”的值。

import re
words = {
    'dog': 5,
    'ant': 6,
    'elephant': 1
}
n = 6
sentences = ['an ant', 'a dog', 'an elephant']
# Get all the popular words
popular_words = [key for key, val in words.items() if int(val)<int(n)]
popular_words = "|".join(popular_words)

for sentence in sentences:
    # Check if sentence contains any of the popular word
    if re.search(rf"{popular_words}", sentence):
        print (sentence)

推荐阅读