swi-prolog中的字符串和列表处理

时间:2015-02-11 09:02:39

标签: prolog artificial-intelligence swi-prolog

我将句子作为输入,然后将其转换为小写。为每个单词创建此句子的列表,然后遍历此列表并搜索特定关键字。

我以不同的方式尝试但仍然无法实现:

转换为小写:

tolower([], []).
tolower([Upper|UpperTail], [Lower|LowerTail]) :-
    char_type(Lower, to_lower(Upper)),tolower(UpperTail, LowerTail).

问题是,它以列表格式给出结果:

1 ?- tolower("Try This STRING", Lower).
Lower = [t, r, y, ' ', t, h, i, s, ' '|...].

在句子中搜索字符串:

substring(Atom, Substring):-
    sub_atom(Atom, _, _, _, Substring).

1 ?- substring('... Where is that?', 'Where').
true .

但是将句子转换为小写,转换为tockens并迭代列表仍然无法使用。这是我想要转换为python的简单代码。

def process(read):
    in_notin_result = (
        ('who',      [],       'person'),
        ('where',    ['what'], 'location'),
        ('why',      [],       'reason'),
        ('how many', [],       'count'),
        ('when',     ['what'], 'time'),
        ('how',      [],       'manner'),
    )
    words = read.split()
    for in_sent, notin_read, result in in_notin_result:
        if in_sent in words and all(disallowed not in read for disallowed in notin_read):
            return result
    return None

def process_link(post_script_link_list, read_str):
    read_str = read_str.lower()

    for item in ('how long', 'how much'):
        if item in read_str:
            return

    for linking in post_script_link_list:
        sub_link = re.search('\((.*?)\)', linking).group(1)

        if sub_link in ['Wq','Ws','Wi','Wd']:
            process_result = process(read_str)
            if process_result is not None:
                return process_result

        elif sub_link in ['Qd']:
            return 'Yes/No' if verify_yesno(post_script_link_list) else 'noresult'

    return 'noresult'

1 个答案:

答案 0 :(得分:2)

SWI-Prolog具有一些惯用NL processing功能,例如

?- tokenize_atom('Try This STRING',L), maplist(downcase_atom,L,D).
L = ['Try', 'This', 'STRING'],
D = [try, this, string].

可以从this pack安装正则表达式支持(简单的Prolog),但是 - 我认为 - 编写DCG更容易。 如果你非常需要正则表达式,比包更高效,那就有旧的XPCE regex接口......