我正在尝试弄清楚如何将我的输入与字典的键进行比较。我想打印出与字典及其值匹配的单词。如果有人可以花一些时间帮助我解决问题,那就太好了:
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")
显然,这种简单的方法有一些缺点,但对于简单的用法就可以了。