Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

load/consult a prolog fragment without loading from a file

88 views
Skip to first unread message

Luke Miller

unread,
Jan 19, 2020, 12:16:19 AM1/19/20
to pyswip
Hi,

I have a prolog script I am generating in python and I would like to load it into the `Prolog()` singleton for quering. I can write it to a file and then call `Prolog().consult` but I was wondering if there is a way to skip that step and just load the snippet direct?

Thanks,
Luke

Stuart Reynolds

unread,
Mar 17, 2020, 12:51:15 PM3/17/20
to pyswip

For simple rule-bases, you can parse a .pl easily. The following will do it. If you have comments, you'll need to add handling for those also.


def statements(s: str):
last = ""
for _s in s.splitlines(keepends=False):
_s = _s.rstrip()
if not _s: continue
if _s.endswith("."):
last += _s[:-1]
yield last
last = ""
else:
last += _s
last += " "
if last:
yield last

def consultString(prolog: Prolog, s: str):
for ass in statements(s):
print(f"---------\n{ass}")
prolog.assertz(ass)


q = open("rulesandfacts.pl").read()
prolog = Prolog()
consultString(prolog,q)

Reply all
Reply to author
Forward
0 new messages