在Prolog中进行字符串处理,例如字符串搜索、迭代、分割等。常见的Prolog教程中并未提供相关信息。
for linking in post_script_link_list:
sub_link = re.search('\((.*?)\)',linking).group(1)
if sub_link in links_list1:
if ('Who').lower() in sent_split or 'Who' in sent_split:
result = 'person'
break
elif (('Where').lower() in sent_split or 'Where' in sent_split) and 'What' not in read_str and 'what' not in read_str:
result = 'location'
break
elif ('Why').lower() in sent_split or 'Why' in sent_split:
result = 'reason'
break
elif ('How many').lower() in read_str or 'How many' in read_str:
result = 'count'
break
elif (('When').lower() in sent_split or 'When' in sent_split) and 'What' not in read_str and 'what' not in read_str:
result = 'time'
break
elif (('How').lower() in sent_split or 'How' in sent_split) and ('How long').lower() not in read_str and 'How long' not in read_str and ('How much').lower() not in read_str and 'How much' not in read_str:
result = 'manner'
break
elif sub_link in links_list2:
check_yn = verify_yesno(post_script_link_list)
if check_yn == 1:
result = 'Yes/No'
break
elif check_yn == 0:
result = 'Not found'
break
break
else:
result = 'Not found'
?- split_string("a.b.c.d", ".", "", L).
ERROR: toplevel: Undefined procedure: split_string/4 (DWIM could not correct goal)
2. 解决方案
2.1 检查字符串是否包含特定子字符串
- 使用 append/3
substring(Codes, Substring):-
append(S, _, Codes),
append(_, Substring, S).
?- substring(".. Where is that?", "Where").
true ;
false.
- 使用 sub_atom/5
substring(Atom, Substring):-
sub_atom(Atom, _, _, _, Substring).
?- substring('... Where is that?', 'Where').
true ;
false.
2.2 分割字符串
- 使用 split_string/4
split_string(String, Delimiter, Substrings) :-
atom_codes(String, Codes),
split_string(Codes, Delimiter, 0, Substrings).
split_string([], _, Accum, Accum).
split_string([Code|Codes], Delimiter, Index, Substrings) :-
( Code == Delimiter ->
Substrings = [Sub|Substrings],
Index is 0,
split_string(Codes, Delimiter, Index, Sub)
; Index > 0 ->
Sub = [Code|Sub],
Index1 is Index + 1,
split_string(Codes, Delimiter, Index1, Sub)
; Sub = [Code],
Index1 is Index + 1,
split_string(Codes, Delimiter, Index1, Sub)
).
?- split_string("a.b.c.d", ".", Substrings).
Substrings = ["a", "b", "c", "d"].
2.3 迭代字符串
- 使用 forall/2
iterate_string(String, Callback) :-
atom_codes(String, Codes),
forall(between(1, length(Codes), Index), Callback(Index, Codes[Index])).
iterate_string("Hello", print_char) :- !.
print_char(Index, Char) :-
write(Index), write(' '), write(Char), nl.
?- iterate_string("Hello", print_char).
1 H
2 e
3 l
4 l
5 o
- 使用 maplist/2
iterate_string(String, Callback) :-
atom_codes(String, Codes),
maplist(Callback, Codes).
iterate_string("Hello", print_char) :- !.
print_char(Char) :-
write(Char), nl.
?- iterate_string("Hello", print_char).
H