首页 > 解决方案 > 如何将用户输入与字典的键进行比较?

问题描述

我试图弄清楚如何将我的输入与字典的键进行比较。我想用字典和它们的值打印出匹配的单词。如果有人可以花一些时间来帮助我解决我的问题,那就太好了:

dictionary = {"nice":"0.5012", "awesome":"0.5766", "thankfull":"0.5891"}

def PNV(saysomething):
    for token in nlp(saysomething):
        while True:
            if token in dictionary:
                print("the word", key, "is same as" + str(token) + 'with the value' + dictionary[value])

标签: pythonloopsdictionaryinputcompare

解决方案


dictionary = {"nice":"0.5012", "awesome":"0.5766", "thankfull":"0.5891"}

def PNV(saysomething):
    for token in nlp(saysomething):        
       if token in dictionary:
            key = str(token)
            value = str(dictionary[token])

            print("the word", key, "is same as" + str(token) + 'with the value' + value)

编辑 基于 OP 评论

dictionary = {"nice":"0.5012", "awesome":"0.5766", "thankfull":"0.5891"}

def nlp(x):
    return x.split()

def PNV(saysomething):
    for token in nlp(saysomething):
        if token in dictionary:
            key = token
            value = dictionary[token]            

            print("the word '{key}' is same as '{token}' with the value {value}".format(key = key, token = token, value = value))


PNV('trying to get a nice result, this is awesome')

生产

the word 'nice' is same as 'nice' with the value 0.5012
the word 'awesome' is same as 'awesome' with the value 0.5766

推荐阅读