如何从Clojure中的文件读取n行 [英] How to read n lines from a file in clojure

查看:39
本文介绍了如何从Clojure中的文件读取n行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用clojure从文件中读取前n行。这是我的代码:

I want to read first n lines from a file using clojure. Here is my code:

(defn read-nth-line [file]
  (with-open [rdr (reader file)]
    (loop [line-number 0]
      (when (< line-number 20)
            (nth (line-seq rdr) line-number)
            (recur (inc line-number))))))

但是当我运行时

 user=> (read-nth-line "test.txt")

 IndexOutOfBoundsException   clojure.lang.RT.nthFrom (RT.java:871)

我不知道为什么会出现这样的错误。

I have no idea why I got such an error.

推荐答案

您的代码会产生边界错误,因为您在同一阅读器上多次调用 line-seq 。如果要从阅读器中获取许多行,则应该只调用一次 line-seq ,然后从该序列中获取所需的行数:

Your code produces an out-of-bounds error because you call line-seq multiple times on the same reader. If you want to get a number of lines from a reader, you should call line-seq only once, then take the desired number of lines from that sequence:

(require '[clojure.java.io :as io])

(defn lines [n filename]
  (with-open [rdr (io/reader filename)]
    (doall (take n (line-seq rdr)))))

示例:

(run! println (lines 20 "test.txt"))

如果 test.txt 包含少于20行,这将只打印文件中的所有行。

If test.txt contains fewer than 20 lines, this will simply print all the lines in the file.

这篇关于如何从Clojure中的文件读取n行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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