Note that there are some explanatory texts on larger screens.

plurals
  1. POProlog - DCG parser with input from file
    text
    copied!<p>As part of a project I need to write a parser that can read a file and parse into facts I can use in my program.</p> <p>The file structure looks as follows: </p> <pre><code>property = { el1 , el2 , ... }. </code></pre> <p>What I want in the end is:</p> <pre><code>property(el1). property(el2). ... </code></pre> <p>I read my file like this: </p> <pre><code>main :- open('myFile.txt', read, Str), read_file(Str,Lines), close(Str), write(Lines), nl. read_file(Stream,[]) :- at_end_of_stream(Stream). read_file(Stream,[X|L]) :- \+ at_end_of_stream(Stream), read(Stream,X), parse(X), % Here I call upon my parser. read_file(Stream,L). </code></pre> <p>Now I have read in several books and online about DCG, but they all explain the same simple examples where you can generate sentences like "the cat eats the bat" etc... When I want to use it for the above example I fail miserably.</p> <p>What I did manage was "parsing" the underneath line: </p> <pre><code>property = el1. </code></pre> <p>to </p> <pre><code>property(el1). </code></pre> <p>with this: </p> <pre><code>parse(X) :- X =.. List, % Reason I do this is because X is one atom and not a list. phrase(sentence(Statement), List), asserta(Statement). sentence(Statement) --&gt; ['=', Gender, Person] , { Statement =.. [Gender, Person] }. </code></pre> <p>I don't even know if I'm using the dcg in a correct way here, so any on help on this would be appreciated. Now the problem I having is, how to do this with multiple elements in my list, and how to handle '{' and '}'.<br> What I really want is a dcg that can handle these types of sentences (with more than 2 elements): <img src="https://i.stack.imgur.com/9ZstF.png" alt="Sentence split in parts"></p> <p>Now I know many people around here refer to the libraries dcg_basics and pio when it comes to dcgs. However, I have an additional problem that when I try to use the library I receive the error:</p> <pre><code>ERROR: (c:/users/ldevriendt/documents/prolog/file3.pl:3): Type error: `text' expected, found `http/dcg_basics' Warning: (c:/users/ldevriendt/documents/prolog/file3.pl:3): Goal (directive) failed: user:[library(http/dcg_basics)] </code></pre> <p>when I do this:</p> <pre><code>:- [library(http/dcg_basics)]. </code></pre> <p>Additional info:</p> <ul> <li>I use the program: <a href="http://lakk.bildung.hessen.de/netzwerk/faecher/informatik/swiprolog/indexe.html" rel="noreferrer">SWI-Prolog-Editor</a> on a Windows environment.</li> </ul> <p>Any help on this would be appreciated!</p> <p><strong>EDIT:</strong> The aim of this is question is to learn more about DCG and its use in parsers.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload