gpt4 book ai didi

python - 从数组的元素中查找所有匹配的单词,保留这些单词,但删除没有这些单词的元素

转载 作者:行者123 更新时间:2023-12-04 10:03:46 25 4
gpt4 key购买 nike

我正在尝试删除数组/json 中没有包含字符串中所有单词的所有元素。例如:

要查找的词:World Hold On

Array [
{
"title" : "Hold On World",
"artist": "some guy"
},
{
"title" : "World, Hold On",
"artist": "some guy"
},
{
"title" : "World Hold On Now",
"artist": "some guy"
},
{
"title" : "World Is Ending",
"artist": "some guy"
}
]

所以对于这个数组,前三个元素应该被保存,但最后一个应该被删除,我尝试过这样的事情:
def removeNonMatches(data, title):
old = title.split(' ')
new = '|'.join(old)
p = re.compile(new, re.I)
for x in data:
if bool(p.search(r"\b("+p+")\b", x['title'], re.IGNORECASE)) == False:
data.remove(x)
return data

data = [
{
"title" : "Hold On World",
"artist": "some guy"
},
{
"title" : "World, Hold On",
"artist": "some guy"
},
{
"title" : "World Hold On Now",
"artist": "some guy"
},
{
"title" : "World Is Ending",
"artist": "some guy"
}
]

title = 'World Hold On'

new_data = removeNonMatches(data, title)

最佳答案

您可以使用

data = [
{
"title" : "Hold On World",
"artist": "some guy"
},
{
"title" : "World, Hold On",
"artist": "some guy"
},
{
"title" : "World Hold On Now",
"artist": "some guy"
},
{
"title" : "World Is Ending",
"artist": "some guy"
}
]
words = ["World", "Hold", "On"]

keep = [item for item in data
if all(word in item["title"] for word in words)]
print(keep)

哪个产量
[{'title': 'Hold On World', 'artist': 'some guy'}, 
{'title': 'World, Hold On', 'artist': 'some guy'},
{'title': 'World Hold On Now', 'artist': 'some guy'}]

要甚至有大写和小写的单词,请使用
words = ["world", "hold", "on"]
keep = [item for item in data
if all(word in item["title"].lower() for word in words)]

关于python - 从数组的元素中查找所有匹配的单词,保留这些单词,但删除没有这些单词的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61693263/

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