【问题标题】:How do I read a text file in MIT/GNU Scheme?如何在 MIT/GNU Scheme 中读取文本文件?
【发布时间】:2019-04-15 17:28:15
【问题描述】:

我一直在学习 SICP,我想应用我目前学到的一些概念。即累积、映射和过滤将帮助我在工作中更有效率。我主要使用 CSV 文件,我知道 MIT/GNU 方案不支持这种文件格式。不过没关系,因为支持 txt 文件,所以我可以将 CSV 文件导出为 txt 文件。

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

【问题讨论】:

    标签: file-io scheme mit-scheme


    【解决方案1】:

    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 上的部分。上面使用的“read”函数只从端口读取下一个 Scheme 对象。还有read-char、read-line等。如​​果你已经从一个文件中读取了所有内容,你会得到那个eof-object的东西吗?将返回 true on - 如果您正在循环读取文件以读取所有内容,这很有用。

    例如将文件中的所有行读取到列表中

    (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
    

    【讨论】:

    • 非常感谢彼得。我现在正在遵循您的建议,并且效果很好。感谢您的帮助。
    【解决方案2】:
    (call-with-input-file "my_file.txt"
      (lambda (port)
        (read port))) ; reads the file's contents
    

    请参阅file portsports 的参考手册。

    【讨论】:

    • 谢谢伊格纽斯。既然您提供了一个简单的示例,我将再次阅读该部分。第一次阅读时,缺乏具体的例子让我很难理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多