python - 检查数据库中的句子是否包含字典中的某些单词
问题描述
我有一个巨大的字典(在 Python 中),其中包含数百万个单词,每个单词都有一个分数,表示受欢迎程度。(注意:我将它作为字典,但我也可以轻松地将它作为数据框使用)。我还有一个包含几百个句子的数据库/SQL 表,每个句子都有一个 ID。
我想看看每个句子是否包含一个流行词,即它是否包含一个分数低于某个数字n的词。遍历每个句子并且每次检查每个单词以查看它是否在字典中以及它的分数是低效的吗?
还有其他更有效的方法吗?
解决方案
这是您可以采用的方法:我的示例代码中的“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)
推荐阅读
- kubernetes-helm - How to push Helm Charts to Azure Container Registry using Drone?
- r - 使用字符串选择数据框中的位置来存储值
- python - How do I look for a tag in xml file and find it's grandparent?
- python - Scrapy in Python order extract with xpaths
- python - ValueError: math domain error whilst using inverse sine rule
- javascript - Vue: How to build bundle for Nuxt with vue-cli-service?
- jupyter-notebook - shell command # can't be carry out when it not used for comments on colab
- office-js - Officejs loaded out side of Excel when putting TaskPane in iframe
- angular - Angular:试图让 ngx-pagination 工作
- r - 如何平均图函数并找到R中的置信带