首页 > 解决方案 > Search for keyword in user input and find the corresponding keyword in dictionary

问题描述

I am doing a search engine, I tried to code so that when the user input some of the keywords, it will search the keyword in the dictionary and print of the key and items.

Canada = {'name': 'Canada', 'continent': 'North America', 'capital': 'Ottawa', 'currency': 'Canadian dollar',
          'population': '32,268,240', 'area': '9,970,610'}
Laos = {'name': 'Laos', 'continent': 'Asia', 'capital': 'Vientiane', 'currency': 'Lao kip',
          'population': '5,924,145', 'area': '236,800'}
Mexico = {'name': 'Mexico', 'continent': 'North America', 'capital': 'Mexico City', 'currency': 'Mexico peso',
        'population': '107,029,400', 'area': '1,958,201'}
key_words = ("Canada", "Mexico", "Laos")
key = ("area", "population", "currency")
user_input = input("Type: ")

for word in user_input.split():
   if word in key_words:
      print()

Could you guy help me with the coding so that: For example: When the user input: "currency of Mexico" it will print out: Mexico peso, or when user input: "area of Laos", it will print out 236,800.

标签: pythondictionaryuser-input

解决方案


不短,但更清晰和更广泛的解决方案。例如查询 like Area and population of Canada,它将打印:

Type: area and population of Canada
results:
area = 9,970,610
population = 32,268,240
from collections import defaultdict

Canada = {'name': 'Canada', 'continent': 'North America', 'capital': 'Ottawa', 'currency': 'Canadian dollar',
          'population': '32,268,240', 'area': '9,970,610'}
Laos = {'name': 'Laos', 'continent': 'Asia', 'capital': 'Vientiane', 'currency': 'Lao kip',
          'population': '5,924,145', 'area': '236,800'}
Mexico = {'name': 'Mexico', 'continent': 'North America', 'capital': 'Mexico City', 'currency': 'Mexico peso',
        'population': '107,029,400', 'area': '1,958,201'}

key = set(["area", "population", "currency"])

# build the forward and reverse indexes
forward_index = [Canada, Laos, Mexico]
reverse_index = defaultdict(set)

for i, description in enumerate(forward_index):
    phrase = ' '.join(['%s %s'%(k,v) for k, v in description.items()])
    words = phrase.lower().split()
    for w in words:
        reverse_index[w].add(i)

# search
user_input = input("Type: ")

res = None
keywords = set()
for word in user_input.lower().split():
    if word in key:
        keywords.add(word)

    posting_set = reverse_index.get(word, None)

    # tolerant search: skip missing words
    if posting_set is None:
        continue

    if res is None:
        res = posting_set
    else:
        res = res.intersection(posting_set)

# print all the results
if res is None or len(keywords) == 0:
    print("<nothing found>")
else:
    print("results:")
    for idx in res:
        desc = forward_index[idx]
        for kw in keywords:
            print("%s = %s" % (kw, desc[kw]))


推荐阅读