Return a list of words from a file

The executioner game is written in my next project. I decided that this would help me deal with strings and input / output files.

I am currently stuck in reading in a file the lines in a list. I am trying to avoid global variables, so can someone point me in the right direction to make this (possibly broken) code into a function that returns a list?

(defun read-word-list ()
  "Returns a list of words read in from a file."
  (let ((word-list (make-array 0 
                 :adjustable t
                 :fill-pointer 0)))
       (with-open-file (stream #p"wordlist.txt")
     (loop for line = (read-line stream)
        while line
          (push line word-list)))
       (select-target-word word-list)))))
+3
source share
2 answers

You can read words as Lisp characters, just a few lines of code:

(defun read-words (file-name)
    (with-open-file (stream file-name)
      (loop while (peek-char nil stream nil nil)
           collect (read stream))))

An example input file is words.txt:

attack attempt attention attraction authority automatic awake 
bright broken brother brown brush bucket building 
comfort committee common company comparison competition

Reading file:

> (read-words "words.txt")
=> (ATTACK ATTEMPT ATTENTION ATTRACTION AUTHORITY AUTOMATIC AWAKE BRIGHT BROKEN BROTHER BROWN BRUSH BUCKET BUILDING COMFORT COMMITTEE COMMON COMPANY COMPARISON COMPETITION)

A case can be saved by including characters in pipes (|) or by declaring them as strings:

|attack| "attempt" ...

Lossless Reading:

> (read-words "words.txt")
=> (|attack| "attempt" ...)
+5
source

, - :

(defun file-words (file)
  (with-open-file (stream file)
    (loop for word = (read-line stream nil)
          while word collect word)))

:

(file-words "/usr/share/dict/words")
+1

Source: https://habr.com/ru/post/1773560/


All Articles