检查列表中是否存在字符串python中的单词

2024-10-05 14:26:28 发布

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

我有将近5万个文档在一个类似这样的mongo集合中:

{"title":"sample title sample title",
 "content":"test content test content",
 "reply":{
           "replyContent":"sample reply content test"
          }
}

我有一系列类似这样的词:

^{pr2}$

我需要匹配我的文档集合中是否存在任何单词形式的wordArr。我必须遍历集合中的每个文档,并搜索array id中给定的单词是否出现在其中的任何一个字段中,即title、content和replyContent


Tags: sample文档testidtitlemongocontent单词
2条回答

假设你的mongo集合在字典中,下面的方法应该有效(对不起,我没有mongo集合的经验)。在

dict = {"title":"sample title sample title",
        "content":"test content test content",
        "reply":{"replyContent":"sample reply content test"}
       }

wordArr = ["sample","test"]

for word in wordArr:

    for key, value in dict.iteritems():

        if word in value:
            print 'Word: `%s` present in `%s`: %s' % (word, key, value)

        if key=='reply':
            for key2,value2 in value.iteritems():
                print 'Word `%s` present in `%s`: %s' % (word, key2, value2)

这将为您提供以下输出:

^{pr2}$

如果只想返回True或False:

d = {"title": "sample title sample title",
     "content": "test content test content",
     "reply": {
         "replyContent": "sample reply content test"
     }
     }

word_set = {"sample", "test"}
def is_present(d, st):
    for v in d.values():
        if isinstance(v, dict):
            for val in d.values():
                if any(word in st for s in val for word in s.split()):
                    return True
        else:
            if any(word in word_set for word in v.split()):
                return True
    return False

print(is_present(d,word_set))

如果有任意级别的嵌套,则可能需要嵌套方法

相关问题 更多 >