2015-02-11 22 views
2

我將句子作爲輸入,然後將其轉換爲小寫。爲每個單詞創建這個句子的列表,然後遍歷這個列表並搜索特定的關鍵字。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' 

回答

2

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

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

支持正則表達式(以純的Prolog)可以從this pack安裝,但是 - 我的觀點 - 它更容易編寫一個DCG 。 如果您非常需要正則表達式,比包的效率更高,那麼舊的XPCE regex接口...