Recognize sentence structure in Prolog

廉价感情. 提交于 2020-01-16 01:12:09

问题


I have a situation where I'm reading in three different types of sentences. They will be of one of the following forms:

_ is a _
A _ is a _
Is _ a _?

I need to be able to recognize which type of sentence was entered and then add to or query my knowledge base.

For example, the user may input:

Fido is a dog.

I would then add that fact to my knowledge base. The user could then enter:

Is Fido a dog?

And the program would answer yes. So far my only idea of recognizing the facts is splitting the sentences on spaces and storing them in a list. Then checking to see where the keywords appear in the list. This is not the best solution since it assumes the "_" characters will always be a single word.

Does anyone have a better solution?


回答1:


The easiest way to split an input into a list of tokens, is to use atomic_list_concat/3. Here is are some example:

?- atomic_list_concat(X,' ','Fido is a dog .').
X = ['Fido', is, a, dog, '.'].

?- atomic_list_concat(X,' ','Is Fido a dog ?').
X = ['Is', 'Fido', a, dog, ?].

You can then use a DCG to parse sentences, return a parse tree of the sentence. The simplest is:

s(fact(isa(X,Y))) --> [X, is, a, Y, '.'].
s(query(isa(X,Y))) --> ['Is', X, a, Y, '?'].

To actually parse use the predicate phrase/2. You can then glue everything together by a parse tree interpreter, call this predicate handle/1:

do(X) :-
   atomic_list_concat(Y,' ',X),
   phrase(s(Z),Y),
   handle(Z).

:- dynamic isa/2.

handle(fact(X)) :- assertz(X), 
    write('Knowledege base extended'), nl.
handle(query(X)) :- 
    (X -> write('Query succeeded'), nl; 
          write('Query failed'), nl).

Here is an example run:

 ?- do('Is Fido a dog ?').
 Query failed

 ?- do('Fido is a dog .').
 Knowledege base extended

 ?- do('Is Fido a dog ?').
 Query succeeded

Bye



来源:https://stackoverflow.com/questions/28920816/recognize-sentence-structure-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!