识别Prolog中的句子结构 [英] Recognize sentence structure in Prolog
问题描述
我遇到一种情况,正在阅读三种不同类型的句子.它们将是以下形式之一:
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.
例如,用户可以输入:
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?
推荐答案
将输入拆分为令牌列表的最简单方法, 是使用atomic_list_concat/3.这是一些示例:
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, ?].
然后您可以使用DCG解析句子,返回解析 句子的树.最简单的是:
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, '?'].
要实际解析,请使用谓词短语/2.你可以 然后通过解析树解释器将所有内容粘合在一起, 称为谓词句柄/1:
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).
这是一个示例运行:
?- do('Is Fido a dog ?').
Query failed
?- do('Fido is a dog .').
Knowledege base extended
?- do('Is Fido a dog ?').
Query succeeded
再见
这篇关于识别Prolog中的句子结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!