如何将文件的内容读入 Lisp 中的列表? [英] How can I read the contents of a file into a list in Lisp?

查看:19
本文介绍了如何将文件的内容读入 Lisp 中的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读入一个文件的内容到一个列表中.到目前为止,我的一些尝试是 -

I want to read in the contents of a file into a list. Some of my attempts so far have been -

(defun get-file (filename)
  (let ((x (open filename)))
    (when x
      (loop for line = (read-line x nil)
     while line do (list line)))
    (close x)))

(defun get-file (filename)
  (let ((x (open filename :if-does-not-exist nil)) (contents (list nil)))
    (when x
      (loop for line = (read-line x nil)
     while line do (cons contents line)))
    (close x) contents))

(defun get-file (filename)
  (let ((x (open filename :if-does-not-exist nil)) (contents nil))
    (when x
      (loop for line = (read-line x nil)
     while line do (append contents line)))
    (close x) contents))

这些都没有用.谁能告诉我一个方法?或者更好 - 如何将所有内容放入数组?

None of these worked. Can anyone tell me a way? Or even better - how to put all of the contents into an array?

推荐答案

我将添加库.

编辑更容易,使用 uiop,它包含在 ASDF 中:

edit even easier, with uiop, which is included in ASDF:

(uiop:read-file-lines "file.txt")

https://common-lisp.net/project/asdf/uiop.html#UIOP_002fSTREAM

也有

(uiop:read-file-string "file")

<小时>

使用亚历山大的read-file-into-string 和分割序列:


With Alexandria's read-file-into-string and split-sequence:

(alexandria:read-file-into-string "file.txt")
(split-sequence:split-sequence #Newline *)

使用str:

(str:lines (str:from-file "file.txt"))

<小时>

关于文件的更多食谱:https://lispookbook.github.io/cl-cookbook/files.html

这篇关于如何将文件的内容读入 Lisp 中的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆