2008-03-29

Utility for working with CSV-files in CLIPS

A couple of months ago I wrote a CLIPS function that could load and assert data from a CSV-file. It was simple but it worked well for my needs. When I started working on The CLIPS Cookbook a couple of weeks ago, a CSV-utility was one of the first things I thought about. Unfortunately, it turned out to be more difficult than I thought to produce an RFC4180 compliant parser so the recipe has remained a placeholder. But, it won't much longer.

Yesterday, I managed to get an implementation to work such that it can handle both import and export from and to CSV-files. I've still got some polishing to do but here's a short introduction to using it.

Assuming we've got a set of link-facts in Working Memory:

CLIPS> (facts)
f-0 (initial-fact)
f-1 (link (title "CLIPSESG") (url "http://groups.google.com/group/CLIPSESG"))
f-2 (link (title "CLIPS") (url "http://clipsrules.sourceforge.net/"))
For a total of 3 facts.
We can export them to a CSV-file using the function CSV-export:
CLIPS> (load "csv.clp")
:!!!!
TRUE
CLIPS> (CSV-export "links.csv" link)
2
The file links.csv looks like this afterwards:
title,url
"CLIPSESG","http://groups.google.com/group/CLIPSESG"
"CLIPS","http://clipsrules.sourceforge.net/"
And if we instead want to load the link-facts from file we can use CSV-import:
CLIPS> (load "csv.clp")
:!!!!
TRUE
CLIPS> (CSV-import "links.csv" link)
2
CLIPS> (facts)
f-0 (initial-fact)
f-1 (link (title "CLIPSESG") (url "http://groups.google.com/group/CLIPSESG"))
f-2 (link (title "CLIPS") (url "http://clipsrules.sourceforge.net/"))
For a total of 3 facts.
Both functions take the filename and the deftemplate as parameters. You can also specify which slots should be exported/imported but that's really not neccessary. However, the first row of the CSV-file must contain slot names (column headers) if you import facts without specifying slots.

Inga kommentarer: