如何将用户输入与字典键进行比较?

时间:2018-12-26 14:48:37

标签: python loops dictionary input compare

我试图弄清楚如何将我的输入与字典的键进行比较。我想打印出与字典及其值匹配的单词。如果有人可以花一些时间来帮助我解决我的问题,那将是很好的事情:

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])

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

现在,我假设nlp()返回一个单词列表,例如字符串,并且如果传递的短语中有一个内部脚本具有不同含义/值的单词,您将简单看一下。如果不是这种情况,请纠正我。

根据上述假设,您可以执行以下操作:

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

def PNV(saysomething):
    for token in nlp(saysomething):
        if token in dictionary:
          #because token is the key I removed the dupplication in print
          print("The word", token, "for me has the following value" + dictionary[token])

text = input("Write some interessting facts: ")
PNV(text)

但是,如果您想说程序的某些单词/标记具有某些等效项,这些等效项是字典中的键,那么简单的条件还不够。 在此特定情况下,一种简单的方法是使用另一台具有等效词/同义词的字典,并首先检查该字典以检索同义词并以以下方式将其用于打印。

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

def getSynonyms(word):
  """Takes a word and returns some synonyms that the program knows"""
  knowledge = {"fantastic":["awesome","wonderful"],
              "good": ["nice","normal"]}

  if word in knowledge: #the word is present
    return knowledge[word]
  else:
    return None

def PNV(saysomething):
    for token in saysomething.split(" "): #using split to simulate npl()
      synonyms = getSynonyms(token)
      words = [token]
      if synonyms:
        words.extend(synonyms) #words and its synonyms
      for word in words:
        if word in dictionary: 
          print("The word", token, "is same as " + word + " with the value " + dictionary[word])

PNV("Hi good day")

这种简单的方法显然有一些缺点,但是对于简单的用法来说是可以的。