簡體   English   中英

如何將用戶輸入與字典鍵進行比較?

[英]How to compare user input with the keys of a dictionary?

我試圖弄清楚如何將我的輸入與字典的鍵進行比較。 我想打印出與字典及其值匹配的單詞。 如果有人可以花一些時間來幫助我解決我的問題,那就太好了:

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

現在,我假設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")

顯然,這種簡單的方法有一些缺點,但是對於簡單的使用而言卻可以。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM