从文件中返回单词列表

And*_*ndy 3 lisp common-lisp

我的下一个项目是写一个刽子手游戏.我认为它可以帮助我刷新字符串并提交I/O.

目前,我一直在阅读一个字符串文件到列表中.我试图避免全局变量,所以有人能指出我正确的方向将这个(可能已损坏的)代码变成一个返回列表的函数吗?

(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)))))
Run Code Online (Sandbox Code Playgroud)

Vij*_*hew 5

您只需几行代码就可以将单词作为Lisp符号读入:

(defun read-words (file-name)
    (with-open-file (stream file-name)
      (loop while (peek-char nil stream nil nil)
           collect (read stream))))
Run Code Online (Sandbox Code Playgroud)

示例输入文件 - words.txt:

attack attempt attention attraction authority automatic awake 
bright broken brother brown brush bucket building 
comfort committee common company comparison competition
Run Code Online (Sandbox Code Playgroud)

阅读文件:

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

可以通过将符号包含在管道(|)中或将它们声明为字符串来保留大小写:

|attack| "attempt" ...
Run Code Online (Sandbox Code Playgroud)

阅读不丢失案例:

> (read-words "words.txt")
=> (|attack| "attempt" ...)
Run Code Online (Sandbox Code Playgroud)