在Prolog中从字符串中分词

时间:2016-01-26 17:18:08

标签: list split prolog dcg

我想从字符串中分割单词并放入Prolog中的列表。

num --> [one] | [two] | [three] | [four] | [five].

?- split("onethreetwofive", Ls).
Ls = [one,three,two,five].             % expected answer

在这里,我想从num拆分带有匹配列表的字符串,并将这些单词放在列表中。我正在使用SWI-Prolog。有任何想法吗?谢谢!

2 个答案:

答案 0 :(得分:4)

使用

:- set_prolog_flag(double_quotes, chars).

num --> "one" | "two" | "three" | "four" | "five".

nums --> "".
nums --> num, nums.

使用SWI-Prolog 7.3.15:

?- phrase(nums, Cs).
Cs = [] ;
Cs = [o, n, e] ;
Cs = [o, n, e, o, n, e] ;
Cs = [o, n, e, o, n, e, o, n, e] ;
...

?- phrase(nums, "onethreetwofive").
true ;
false.

OK!接下来,我们从num//0升级到num//1,从nums//0升级到nums//1

num(one)   --> "one".
num(two)   --> "two".
num(three) --> "three".
num(four)  --> "four".
num(five)  --> "five".

nums([])     --> "".
nums([X|Xs]) --> num(X), nums(Xs).

让我们运行OP建议的查询!

?- phrase(nums(Ls), "onethreetwofive").
Ls = [one, three, two, five] ;
false.

答案 1 :(得分:0)

让我们试试这段代码 while (reader.Read()) { //string s = "tpno"; sms sm = new sms(reader.GetString("tpno".Split(","))); sm.Show(); }
:-set_prolog_flag(double_quotes, codes).
any(A,K) --> {member(S,K)}, S, {atom_codes(A, S)}.
num(S) --> any(S, ["one","two","three","four","five"]).
nums([]) --> "".

nums([X|Xs]) --> num(X), nums(Xs).

好的,现在让我们运行查询 split(Str,Ls):-phrase(nums(Ls),Str).
?- split("onethreetwofive", Ls).