我的下一个项目是写一个绞刑者游戏。我认为它可以帮助我温习字符串和文件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)))))发布于 2010-11-08 13:50:27
您只需几行代码即可将单词读入为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" ...)发布于 2010-11-08 21:26:20
如果单词是每行一个,你可以这样做:
(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")https://stackoverflow.com/questions/4120973
复制相似问题