Prolog DCG的问题

时间:2011-01-28 10:49:51

标签: prolog nlp grammar dcg

该项目是关于将半自然语言翻译成SQL表格。代码:

label(S) --> label_h(C), {atom_codes(A, C), string_to_atom(S, A)}, !.

label_h([C|D]) --> letter(C), letters_or_digits(D), !.

letters_or_digits([C|D]) --> letter_or_digit(C), letters_or_digits(D), !.
letters_or_digits([C]) --> letter_or_digit(C), !.
letters_or_digits([]) --> "", !.

letter(C) --> [C], {"a"=<C, C=<"z"}, !.
letter(C) --> [C], {"A"=<C, C=<"Z"}, !.
letter_or_digit(C) --> [C], {"a"=<C, C=<"z"}, !.
letter_or_digit(C) --> [C], {"A"=<C, C=<"Z"}, !.
letter_or_digit(C) --> [C], {"0"=<C, C=<"9"}, !.

table("student").

sbvr2sql --> label(Name), " is an integer.", {assert(fields(Name, "INT"))}.
sbvr2sql --> label(Name), " is a string.", {assert(fields(Name, "VARCHAR(64)"))}.

sbvr2sql(Table, Property)  --> label(Table), " has ", label(Property), ".".

以下是它如何正常工作:

?- sbvr2sql("age is an integer.", []).
true 

?- sbvr2sql("firstName is a string.", []).
true.

?- sbvr2sql(T, P, "student has firstName.", []).
T = "student",
P = "firstName".

?- fields(F, T).
F = "age",
T = [73, 78, 84] n
F = "firstName",
T = [86, 65, 82, 67, 72, 65, 82, 40, 54|...].

?- sbvr2sql(T, P, "student has firstName.", []), fields(P, _).
T = "student",
P = "firstName".

但它在这里不起作用:

?- table(T).
T = [115, 116, 117, 100, 101, 110, 116]. % "student"

?- sbvr2sql(T, P, "student has firstName.", []), table(T).
false.

显然它无法识别table("student")为真。它将“学生”识别为如上所示的标签。是什么给了什么?

1 个答案:

答案 0 :(得分:3)

我无法重现错误,但我怀疑它可能在您的label/3规则中。当我使用此规则的以下定义时:

label([C|S]) -->
    [C], {[Sp|_] = " ", C \= Sp, [Dot|_] = ".", C \= Dot}, !,
    label(S).
label([],X,X).

我得到了正确的结果:

?- sbvr2sql(TS, PS, "student has firstName.", []), table(TS),
   atom_codes(P,PS), atom_codes(T,TS).
TS = [115, 116, 117, 100, 101, 110, 116],
PS = [102, 105, 114, 115, 116, 78, 97, 109, 101],
P = firstName,
T = student.

一般来说,我建议在进行DCG操作之前将字符串标记为原子列表。这样,由于Prolog笨拙的字符串输出,调试起来要容易得多。