在Clojure中读取文件并忽略第一行?

3

使用这个答案中的代码,我已经

(defn repeat-image [n string]
  (println (apply str (repeat n string))))

(defn tile-image-across [x filename]
  (with-open [rdr (reader filename)]
    (doseq [line (line-seq rdr)]
      (repeat-image x line))))

如何将ASCII图像水平平铺。现在,我该如何“忽略”第一行?我这样做的原因是每个图像的坐标(例如“20 63”)作为第一行,而我不需要这一行。我尝试了一些方法(保持索引,模式匹配),但我的方法感觉很牵强。

1个回答

6
假设您想跳过文件的第一行,并像在tile-image-across中一样处理其余行,您可以将(line-seq rdr)替换为:
(next (line-seq rdr))

事实上,您可能应该将选择相关行和处理分开考虑:
;; rename repeat-image to repeat-line

(defn read-image [rdr]
  (next (line-seq rdr)))

(defn repeat-image! [n lines]
  (doseq [line lines]
    (repeat-line n line)))

with-open中使用:

(with-open [rdr ...]
  (repeat-image! (read-image rdr)))

如果你的文件中包含多个图片,并且你需要跳过每个图片的第一行,最好的方法是编写一个函数将行序列划分为图像序列(如何完成取决于文件的格式),然后将其映射到 (line-seq rdr) 上,并将 (map next ...)) 映射到结果上。
(->> (line-seq rdr)
     ;; should partition the above into a seq of seqs of lines, each
     ;; describing a single image:
     (partition-into-individual-image-descriptions)
     (map next))

注意:如果使用一个懒惰的partition-into-individual-image-descriptions函数,则会产生一个懒惰序列的懒惰序列;您需要在with-open关闭读取器之前使用它们。


澄清一下,每个图像都在单独的文件中。 - Emil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接