0

In a multi-line text file, determine the number of words in each line and enter information about this in a separate line of the new file in the form: line # contains words.The file contains only words, for example "Marry Christmas" is 1 line 2 words.

I have an example, but it's not readable from a file, and why does it always return false?

    main :-
    open('in.txt', read, Str),
    read_file(Str,Lines),
    close(Str),
    write(lenght(Lines)),
    word_count(Lines).

read_file(Stream,[]) :-
    at_end_of_stream(Stream).

read_file(Stream,[X|L]) :-
    \+ at_end_of_stream(Stream),
    read(Stream,X),
    read_file(Stream,L).

word_count(C):- Lines(LS),
    count(LS, C), true.
count([], 0).
count([L|LS], C) :- split_string(L, " ", "", W),
    length(W, N1), write(lenght(W,N1)), count(LS, N2), C is N1 + N2, true.
  • 1
    See https://stackoverflow.com/questions/4805601/read-a-file-line-by-line-in-prolog for a few approaches. "*why does it always return false?*" - because it's exhausted the search space and found no more solutions which fit your code. – TessellatingHeckler Dec 08 '21 at 05:02
  • You need to understand you problem; then you need to understand the code you are writing. You can't just throw things at the wall until something sticks. "Not readable from a file" yes because this snippet you show **does not read from a file**. It hurts me to say it but if you need to program, you either do as programmers do or find a way to find a programmer to do it for you. This is not intended as a negative comment, on the contrary. – TA_intern Dec 08 '21 at 10:19
  • Ok, I added the read part from the file. It reads into a variable Lines. How to correctly pass this variable to the predicate now word_count? – Марьяна Dec 08 '21 at 11:14
  • This is not going to work. The code you have reads _Prolog terms_, not arbitrary text. – TA_intern Dec 08 '21 at 14:34
  • So don't I have a list from a file in a variable Lines? – Марьяна Dec 08 '21 at 14:36
  • I don't know what you have. I suspect you have some material given to you by the same person who gave you this task. If I were you, I would start reading that material, to get some grasp of the bigger picture. – TA_intern Dec 08 '21 at 14:37
  • No, unfortunately I have no material, here I'm looking for help on how to implement correct reading from a file into a variable, I can't even find such an example in open sources. – Марьяна Dec 08 '21 at 14:53

0 Answers0