gpt4 book ai didi

lisp - 从文件中返回单词列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:58 24 4
gpt4 key购买 nike

我的下一个项目是编写刽子手游戏。我认为它可以帮助我复习字符串和文件 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)))))

最佳答案

只需几行代码,您就可以将单词作为 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" ...)

关于lisp - 从文件中返回单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4120973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com