2010-11-08 64 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") 
相關問題