简体   繁体   中英

Search a string in a file in Prolog

I must search a string in a file, and i assert a fact if the term is present.

For example

My file:

  title"Fast and furious"
  year"2013"
  actor"Vin Diesel"

assert(title(Fast and furious)),
assert(year(2013)),
assert(actor(Vin Diesel)).

How can I do?

EDIT:

Is it possibile extract a part of a string?

<title>Fast and Furious</title>

I would get only "Fast and Furious" and then i would assert(title(Fast and Furious)). Is it possibile? I don't use library(sgml) of swi_prolog.

In SWI-Prolog the easy way is using phrase_from_file :

file --> "title", dquo(Title), "\nyear", dquo(Year), "\nactor", dquo(Actor),
   {assert(title(Title)), assert(year(Year)), assert(actor(Actor))}.

dquo(A) --> "\"", any(S), "\"", {atom_codes(A, S)}.

any([]) --> [].
any([C|Cs]) --> [C], any(Cs).

edit : DCG are plain, declarative Prolog: to use different delimiters than double quotes, try

title(T) --> "<title>", any(S), "</title>", {atom_codes(T, S)}.

I hope you will appreciate the flexibility of DCG rules. SWI-Prolog has an helper library with some handy predefined rule.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM