Read a file in clojure and ignore the first line?

偶尔善良 提交于 2021-02-09 11:57:43

问题


Using code from this answer, I have

(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))))

...to tile an ascii image horizontally. Now, how would I be able to "ignore" the first line? The reason I'm doing this is each image has the coordinates (for example "20 63") as the first line, and I don't need the line. I tried some ways (keeping an index, pattern matching) but my approaches felt contrived.


回答1:


Assuming you'd like to skip the first line of the file and process the remaining lines as you do in tile-image-across, you can simply replace (line-seq rdr) with

(next (line-seq rdr))

In fact, you should probably factor out selecting the relevant lines and the processing:

;; 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)))

Use inside with-open:

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

If instead your file holds multiple images and you need to skip the first line of each, the best way would be to write a function to partition the seq of lines into a seq of images (how that'd be done depends on the format of your file), then map that over (line-seq rdr) and (map next ...)) over the result:

(->> (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))

NB. with a lazy partition-into-individual-image-descriptions this will produce a lazy seq of lazy seqs; you'll need to consume them before with-open closes the reader.



来源:https://stackoverflow.com/questions/19013616/read-a-file-in-clojure-and-ignore-the-first-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!