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

时间:2019-02-15 06:56:33

标签: python string

我目前正在使用一个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
  

我的文件包含3个狂欢节实例(班加罗尔狂欢节,孟买狂欢节和德里狂欢节)

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

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"
      }]
    }
}

1 个答案:

答案 0 :(得分:1)

您可以添加另一个循环并使用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

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

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