2017-09-28 5 views
0

新しいpythonとプログラミングの世界です。ポイントに達する。私はこのコードを実行し、入力を入れて鶏を言うと、それは2つの脚の動物として返信されます。しかし、私は間違いなく宇宙猿のような間にスペースを持っている2つの単語のもののための返事を得る(それは私の辞書に表示されますが)どのように私はそれを解決するのですか?辞書の2ワードのキーを検索する

私の辞書: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 
+1

なぜユーザー入力を分割していますか?入力全体を辞書のキーとして使用するだけです。 – Barmar

+0

通常、ユーザの入力は "what is chicken"のようになりますので、私のコードは辞書のチキンを検出し、それに基づいて答えを返します。 – saitama

+0

"what is"のような雑音を取り除く方法を知っているパーサーを設計する必要があります。 – Barmar

答えて

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)) 
+0

ty @Anton vBR。実際に私が望むのは、どんな言葉を入れてもいいということです。例:魚は何ですか?あなたのコードを使って、その文が辞書にないので、答えがないことに気づくでしょう。私のコードは、一方で、文を分割し、辞書に一致するすべての単語をチェックするのに役立ちます。問題は、私は2つの単語と文字列を一致させることはできません。例:宇宙猿。私はそれが1つの単語を検出するだけ原因を呼び出すことはできません。私は本当にあなたの助けに感謝します – saitama

+0

@saitamaパーフェクト!今あなたは物事をもっとはっきりと説明しています。これは私たちが最初から望んでいたものです。しかし、まだ多くの質問があります:同じ行の複数の入力はどうでしょうか?それともちょうど最初のものですか?例のために私の更新されたコードを見てください。キーは異なる組み合わせのリストを作成する* combos **変数です。それを理解するには、印刷(コンボ)を使用してください。 –

0

はあなたのコードの問題は、あなたがfor w in input_lsを使用する場合で、何を渡すと、 "宇宙猿" でした、それは宇宙を探して、それから猿を探します。あなたは、この特定のスクリプトを用いて所望の結果をしたい場合は、それはそれは何を返さないと、個々の単語の配列、にあなたの文字列を回すので、私はまたinput_ls = user_inputinput_ls = user_input.split(" ")を変更し、この

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 

ノートのように見えると思います「再私は仕事のためにクロックに出ていたが、

if input_ls in dictionary2: 
    processor["dictionary2"] = True 
    processor["dictionary_lookup"].append(input_ls) 

--edit--

ここにあなたが特定の語句の代わりに、個々の単語を検索しようとしている場合を探して、この重要な変更を行いました今私は家にいます。彼の方が良い。辞書を使ってこの目標を達成しようとするとき、私はそれをやったのです。辞書を反復処理しようとすると

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.itervaluesのためのキーとval
dictionary2.iterkeys両方のための
dictionary2.iteritemsを()()()あなたの価値のために

+0

それでも、私はこれが最善の方法だとは言いませんが、それは質問に答えます – saniboy

+0

あなたの助けに感謝@ saniboy。その本当のあなたのコード。しかし、私はそれがより柔軟になりたい、ユーザーが入力することができます "宇宙猿は何ですか?"コードは、 "スペース"と "猿"を検出し、両方を組み合わせ、dictをチェックして結果を与える。私は本当に難しいことを知っています。私の間違い。とにかく感謝:) – saitama

0

これは面白い問題だったので、回答が選択されても私は答えを返しました。

この回答は、単語の代わりに人間のような質問をすることができます。

実際の機械学習の場合は、nltkが最適です。始めには、以下のようなものを使うことができます。

組み込みライブラリdifflibを辞書キーとの照合に使用し、どちらが高い確率であるかを決定しました。

警告:例外処理は実装されていません。それはただ最大の可能性のあるマッチを拾うだけです。

次に、reを使用して、キーの単語をanswerから削除し、すべてを戻します。これは、キー値を表示するだけでなく、より自然な答えを提供します。

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 
>>> 
+0

@Anil_Mありがとうございます。あなたの答えは、私が望むものに最も近いと言わなければなりません。もう一度、ありがとう:) – saitama

+0

私はあなたが私の答えを選択することができますし、任意の投票をいただければ幸いです。 –