gpt4 book ai didi

python - 如何查找与一个或多个单词的输入查询匹配的所有字符串

转载 作者:行者123 更新时间:2023-12-01 08:20:06 25 4
gpt4 key购买 nike

我目前正在使用一个 JSON 文件,其中存储了许多剧院位置以及与每个位置对应的代码。

我目前正在做的是,如果用户输入某个位置,我将返回相应的代码。我想做的是,分割输入字符串并在 JSON 文件中搜索相应的关键字,然后返回适当的位置匹配及其代码。

这是我到目前为止的代码:

queryname = input("Enter the Venue Name:")

def query():
for d in data['BookMyShow']['arrVenues']:
if d['VenueName'] == queryname:
yield d['VenueCode']

f1 = query()
for f in f1:
print(f)

我要将 input() 语句更改为 input.split(),以便可以存储各个关键字。但是我不确定如何更改我的函数以便搜索每个单独的关键字并返回相关字符串。

所以,一个例子是这样的:

Enter the Venue Name:
Carnival

My file contains 3 instances of Carnival (Carnival Bangalore, Carnival Mumbai and Carnival Delhi)

我希望它返回的输出是这样的:

Carnival Bangalore A000
Carnival Mumbai A001
Carnival Delhi A002

这就是我的数据文件的片段:

{
"BookMyShow": {
"arrVenues": [
{
"VenueCode": "AAAD",
"VenueName": "Khinvasara Cineplex (Apsara Cinema): Aurangabad",
"VenueSeq": "9999"
},
{
"VenueCode": "AACM",
"VenueName": "Anjana Chitra Mandir: Raniganj",
"VenueSeq": "9999"
},
{
"VenueCode": "AAME",
"VenueName": "Shree Ram Cinema: Deesa",
"VenueSeq": "9999"
},
{
"VenueCode": "AASH",
"VenueName": "Adarsh Chitra Mandir: Bhandara",
"VenueSeq": "9999"
},
{
"VenueCode": "ABCC",
"VenueName": "Abhay Cinema: Chandrapur",
"VenueSeq": "9999"
}]
}
}

最佳答案

您可以添加另一个循环并使用 in 运算符:

def query():
keywords = queryname.split(' ')
for d in data['BookMyShow']['arrVenues']:
for keyword in keywords:
if(keyword in d['VenueName']):
yield(d) # you should yield the whole venue because you want to print both the venue code and name later on
break # this is so that we don't yield it twice when multiple keywords match

要以您显示的格式打印 field ,您可以执行以下操作:

f1 = query()
for f in f1:
print(f['VenueName'], f['VenueCode'])

对于不区分大小写,只需将两边转换为小写/大写:

if keyword.lower() in d['VenueName'].lower():

如果您只想匹配包含所有关键字的场所,请使用以下命令:

def query():
keywords = queryname.split(' ')
for d in data['BookMyShow']['arrVenues']:
reject = False
for keyword in keywords:
if not (keyword.lower() in d['VenueName'].lower()):
reject = True
break
if not reject:
yield d

关于python - 如何查找与一个或多个单词的输入查询匹配的所有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54704095/

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