我是python和编程世界的新手。达到目的。当我运行这个代码并输入输入让我说鸡,它会回复为两腿动物。但我不能得到两个字的回复,就像空间猴子之间有空间(虽然它出现在我的字典中)所以我该如何解决呢?
我的字典:example.py
dictionary2 = {
"chicken":"chicken two leg animal",
"fish":"fish is animal that live under water",
"cow":"cow is big vegetarian animal",
"space monkey":"monkey live in space",
我的代码:test.py
from example import *
print "how can i help you?"
print
user_input = raw_input()
print
print "You asked: " + user_input + "."
response = "I will get back to you. "
input_ls = user_input.split(" ")
processor = {
"dictionary2":False,
"dictionary_lookup":[]
}
for w in input_ls:
if w in dictionary2:
processor["dictionary2"] = True
processor["dictionary_lookup"].append(w)
if processor["dictionary2"] is True:
dictionary_lookup = processor["dictionary_lookup"][0]
translation = dictionary2[dictionary_lookup]
response = "what you were looking for is: " + translation
print
print "Response: " + response
答案 0 :(得分:0)
您的代码存在的问题是当您使用for w in input_ls
时,您传递的内容是"空间猴子",它寻找空间,然后它寻找猴子。如果您希望使用此特定脚本获得所需结果,则它看起来像这样
print "how can i help you?"
print
user_input = raw_input()
print
print "You asked: " + user_input + "."
response = "I will get back to you. "
input_ls = user_input
processor = {
"dictionary2":False,
"dictionary_lookup":[]
}
if input_ls in dictionary2:
processor["dictionary2"] = True
processor["dictionary_lookup"].append(input_ls)
if processor["dictionary2"] is True:
dictionary_lookup = processor["dictionary_lookup"][0]
translation = dictionary2[dictionary_lookup]
response = "what you were looking for is: " + translation
print
print "Response: " + response
请注意,我还将input_ls = user_input.split(" ")
更改为input_ls = user_input
,因为这会将您的字符串转换为单个字词的数组,如果您使用的话,这些字词将无法返回您正在查找的字词。\ n&#39}重新尝试查找特定的短语而不是单个单词,并在此处进行了这一重要更改
if input_ls in dictionary2:
processor["dictionary2"] = True
processor["dictionary_lookup"].append(input_ls)
- 编辑 -
我不得不出去工作,但现在我回家了,我可以更好地解决这个问题。当试图使用字典来实现这个目标时,我会如何做到这一点。
dictionary2 = {
"red":"the color red",
"blue":"fish is animal that live under water",
"red and blue":"these colors make blue",
"blue and yellow":"these colors make green"
}
user_input = raw_input('what would you like?\t')
user_input = user_input.split(' ')
print
for word in user_input:
for key,val in dictionary2.iteritems():
if word in key:
print '%s: %s' % (key,val)
尝试迭代字典时,您需要使用以下任一项:
dictionary2.iteritems()用于key和val
dictionary2.iterkeys()为你的钥匙
你的值的dictionary2.itervalues()
答案 1 :(得分:0)
即使选择了答案,我也会重新回答我的答案,因为这是一个有趣的问题,而且我在给定时间内接近公平的解决方案。
这个答案可以带问人类问题,而不仅仅是单词。
虽然,对于真正的机器学习nltk
是更好的选择。首先,我们可以使用下面的内容。
它使用内置库difflib
来匹配字典键的问题,并确定哪个具有更高的概率。
警告:未实现异常处理。它只会获得最大可能的匹配。
然后我们使用re
从回答中删除密钥中的单词并将所有内容重新组合在一起。这比仅显示键值提供了更自然的答案。
import re
from difflib import SequenceMatcher
def similarity(a, b):
return SequenceMatcher(None, a, b).ratio()
dictionary2 = {
"chicken":"chicken two leg animal",
"fish":"fish is animal that live under water",
"cow":"cow is big vegetarian animal",
"space monkey":"monkey live in space",}
user_input = raw_input("User Question:")
#Check which key has greater probability match
similarity_list = []
for i in dictionary2.keys():
similarity_list.append((i,similarity(user_input,i)))
key_match = max(similarity_list, key=lambda x:x[1])
uin = ('|'.join(key_match[0].split()))
p = re.compile(r"\b(" + uin + ")\\W", re.I)
ans = p.sub('', dictionary2[key_match[0]])
print "answer: {} {}".format(key_match[0], ans)
结果
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
User Question:what is a chicken?
answer: chicken two leg animal
>>> ================================ RESTART ================================
>>>
User Question:Where does space monkey live?
answer: space monkey live in space
>>> ================================ RESTART ================================
>>>
User Question:Where does fish live?
answer: fish is animal that live under water
>>> ================================ RESTART ================================
>>>
User Question:what is a cow?
answer: cow is big vegetarian animal
>>>
答案 2 :(得分:0)
你需要解释你的目的,以获得更好的帮助。 在你的情况下,你似乎只对查找单词感兴趣,然后这段代码就足够了。请注意.format()语法可以彻底清理代码。
更新代码:现在使用输入中找到的组合创建列表。然而,这可能需要修改以满足需求。
dictionary2 = {
"chicken":"chicken two leg animal",
"fish":"fish is animal that live under water",
"cow":"cow is big vegetarian animal",
"space monkey":"monkey live in space"}
print("how can i help you?")
user_input = raw_input()
print("You asked: {}.".format(user_input))
split = user_input.split(" ")
combos = [' '.join(split[x:y]) for x in range(len(split)) for y in range(len(split)+1) if ' '.join(split[x:y]) != ""]
# Create an empty dictionary to insert found item
response = {}
for item in combos:
if dictionary2.get(item):
response[item] = "what you were looking for is: {}.".format(dictionary2[item])
# If dictionary is empty do this
if not response:
print("Response: I will get back to you!")
# If not, loop over keys(k) and values(v) and print them with an index(ind)
for ind, (k,v) in enumerate(response.iteritems()):
print("Response {}: {} ({})".format(ind+1, v, k))