从Common Lisp中的文本文件读取数组 [英] Reading an array from a text file in Common Lisp
问题描述
我正在尝试从文本文件中读取Lisp中的数据(实际上是一个数组).
我尝试使用with-open-file
和read-line
东西,但无法实现我的目标.我正在寻找的内容等同于在MATLAB中执行data=load('filename.txt')
,因此我得到一个名为data
的数组,该数组已将所有信息加载到filename.txt
中.
I am trying to read data (which is actually an array) in Lisp from a text file.
I tried to use with-open-file
and read-line
stuff but could not achieve my goal. What I am looking for is equivalent to doing data=load('filename.txt')
in MATLAB, so that I get an array called data
which has loaded the whole information in filename.txt
.
文本文件的格式为
1.0 2.0 3.0 ...
1.5 2.5 3.5 ...
2.0 3.0 4.0 ...
.....
大小也可能有所不同.提前非常感谢.
The size may also vary. Thanks a lot in advance.
推荐答案
做到这一点的基本方法是使用with-open-file
获取输入流,read-line
在loop
中获取行,parse-number
(来自相同名称的库)将字符串转换为数字.提到的所有库都可以从 Quicklisp 中获得.
The basic way to do that is to use with-open-file
for getting the input stream, read-line
in a loop
to get the lines, split-sequence
(from the library of the same name) to split it into fields, and parse-number
(from the library of the same name) to transform the strings into numbers. All libraries mentioned are available from Quicklisp.
只是为了入门,这是一个未经验证的简单版本:
Just to get you started, this is a simple version without validation:
(defun load-array-from-file (filename)
(with-open-file (in filename
:direction :input)
(let* ((data-lol (loop :for line := (read-line in nil)
:while line
:collect (mapcar #'parse-number:parse-number
(cl-ppcre:split "\\s+" line))))
(rows (length data-lol))
(columns (length (first data-lol))))
(make-array (list rows columns)
:initial-contents data-lol))))
您应该添加一些检查,并考虑如果不满足要求您想得到什么:
You should add some checks and think about what you want to get in case they are not fulfilled:
- 行的长度都一样吗?
- 所有字段都是有效数字吗?
这篇关于从Common Lisp中的文本文件读取数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!