Discussions related to Visual Prolog
dcgreenwood
Posts: 24
Joined: 16 Jan 2021 1:33

Importing a list

Unread post by dcgreenwood »

I would like to be able to pull a long list of words from a file into a list. I know how to do that if each word is a fact, and I think I could do it by making a single fact with the long list of words delimited as a list in that fact, but is there a command that would allow a file with delimited words to be read directly into a list?
Input would be a text file
word1,word2,word3 etc
or
word1
word2
word3
etc.


End product would be

Code: Select all

Wordlist = [Word1,Word2,Word3...]
So, how can I read that file into a list variable?
Harrison Pratt
VIP Member
Posts: 353
Joined: 5 Nov 2000 0:01

Re: Importing a list

Unread post by Harrison Pratt »

Here is a very simple way with no error checking or special processing.

The code below assumes a file named WordsAcross.txt with the this sample text in it, Note the embedded carriage return between five and six:

Code: Select all

one,two,three,four,five, six,seven,eight,nine

Code: Select all

class predicates     fileToList : (string FileName, string Separator) -> string_list StringList. clauses     fileToList(FileName, Separator) = StringList :-         FileAsString = file::readString(FileName),         StringList = string::split(FileAsString, Separator).   clauses     run() :-         SSnl = fileToList("WordsAcross.txt", "\n"),         stdio::write("\nString per line:\n", SSnl, "\n"),         %         SScomma = fileToList("WordsAcross.txt", ","),         stdio::write("\nComma-separated:\n", SScomma),         _ = stdio::readLine().
But suppose you want to do some filtration on a very large one-word-per-line file, then it may be better for you to use stream processing and list comprehension:

Code: Select all

class predicates     fileToList2 : (string FileName, string PrefixWanted) -> string_list StringList. clauses     fileToList2(FileName, PrefixWanted) = StringList :-         Input = inputStream_file::openFileBom(FileName),         StringList =             [ S ||                 Input:repeatToEndOfStream(),                 S = Input:readLine(),                 string::hasPrefix(S, PrefixWanted)             ],         Input:close().
dcgreenwood
Posts: 24
Joined: 16 Jan 2021 1:33

Re: Importing a list

Unread post by dcgreenwood »

Thanks!
Post Reply