如何在MIT / GNU Scheme中读取文本文件?

问题描述 投票:1回答:2

我一直在经历SICP,我想应用到目前为止我学到的一些概念。即累积,地图和过滤器将帮助我提高工作效率。我主要使用CSV文件,我知道MIT / GNU方案不支持这种文件格式。但这没关系,因为我可以将CSV文件导出到txt文件,因为支持txt文件。

现在我阅读手册的第14节输入/输出,坦率地说,缺乏具体的例子并没有帮助我开始。所以我希望你们中的一些人能给我一个良好的开端。我有一个文本文件foo.txt,包含国家列表的变量和观察结果。我只想将此文件读入Scheme并操作数据。谢谢您的帮助。任何示例代码都会有所帮助。

file-io scheme mit-scheme
2个回答
2
投票

Scheme提供了一些从文件中读取的方法。您可以使用“打开/关闭”样式,如下所示:

(let ((port (open-input-file "file.txt")))
  (display (read port))
  (close-input-port port))

您还可以使用igneus的回答,它将端口传递给过程,并在过程结束时自动关闭端口:

(call-with-input-file "file.txt"
  (lambda (port)
    (display (read port))))

最后,我最喜欢的是,更改当前输入端口以从文件中读取,运行提供的过程,关闭文件并在最后重置当前输入端口:

(with-input-from-file "file.txt"
                      (lambda ()
                        (display (read))))

您还需要阅读有关Input Procedures的部分。上面使用的“读取”函数只从端口读取下一个Scheme对象。还有read-char,read-line等。如​​果你已经读过文件中的所有内容,你会得到一些eof-object?将返回true - 如果您循环浏览文件以读取所有内容,则非常有用。

例如读取文件中的所有行,进入列表

(with-input-from-file "text.txt"
  (lambda ()
    (let loop ((lines '())
               (next-line (read-line)))
       (if (eof-object? next-line) ; when we hit the end of file
           (reverse lines)         ; return the lines
           (loop (cons next-line lines) ; else loop, keeping this line
                 (read-line))))))       ; and move to next one

0
投票
(call-with-input-file "my_file.txt"
  (lambda (port)
    (read port))) ; reads the file's contents

请参阅file portsports上的参考手册。

© www.soinside.com 2019 - 2024. All rights reserved.