从文件中返回单词列表

时间:2010-11-08 03:10:55

标签: 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)))))

2 个答案:

答案 0 :(得分: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

阅读文件:

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

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

|attack| "attempt" ...

不丢失案例阅读:

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

答案 1 :(得分:2)

如果单词是每行一个,你可以这样做:

(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")