2010-11-08 70 views
3

我的下一个项目是编写一个hang子手游戏。我想这会帮助我刷新字符串和文件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))))) 
+1

问题的标题与问题的文字相关的标题如何? – 2010-11-08 07:08:08

+0

我开始问一个问题,转到另一个问题,忘记改变它。哎呦。 – Andy 2010-11-08 14:31:57

回答

5

可以读入的词作为Lisp的符号,用的代码,只需几行:

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

例输入文件 - words.txt:

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

读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) 

case cou

|attack| "attempt" ... 

阅读不失情况:

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

如果你以这种方式使用'read',你总是应该把'* read-eval *'绑定到nil。另一方面,我觉得用一些用户输入的符号填充一个包是有问题的。我强烈喜欢使用字符串。 – Svante 2015-01-02 14:35:25

1

如果字是每行一个,你可以做类似|()或者声明为字符串LD通过管道封闭的符号被保留这个:

(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") 
相关问题