gpt4 book ai didi

python - Pymongo Regex $所有多个搜索词

转载 作者:行者123 更新时间:2023-12-01 05:05:31 24 4
gpt4 key购买 nike

我想搜索 MongoDB,以便只获得所有 x 在某些配置中一起在键中找到的结果。

collected_x =  ''
for x in input:
collected_x = collected_x + 're.compile("' + x + '"), '
collected_x_cut = collected_x[:-2]

cursor = db.collection.find({"key": {"$all": [collected_x_cut]}})

这并没有带来预期的结果。如果我自己输入倍数x,就可以了。

cursor = db.collection.find({"key": {"$all": [re.compile("Firstsomething"), 
re.compile("Secondsomething"),
re.compile("Thirdsomething"),
re.compile("Fourthsomething")]}})

我做错了什么?

最佳答案

您正在 for 循环中构建一个字符串,而不是 re.compile 对象列表。你想要:

collected_x = []                            # Initialize an empty list

for x in input: # Iterate over input
collected_x.append(re.compile(x)) # Append re.compile object to list

collected_x_cut = collected_x[:-2] # Slice the list outside the loop

cursor = db.collection.find({"key": {"$all": collected_x_cut}})

一个简单的方法是使用 map构建列表:

collected = map(re.compile, input)[:-2]
db.collection.find({"key": {"$all": collected}})

或者list comprehension :

collected = [re.compile(x) for x in input][:-2]
db.collection.find({"key": {"$all": collected}})

关于python - Pymongo Regex $所有多个搜索词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25126255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com