问题描述
使用此答案中的代码,我有
(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"),而我不需要该行.我尝试了一些方法(保持索引,模式匹配),但是我的方法感觉很虚构.
...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.
推荐答案
假设您要跳过文件的第一行,并像在 tile-image-across
中一样处理其余行>,您只需将(line-seq rdr)
替换为
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)))
在 with-open
内部使用:
(with-open [rdr ...]
(repeat-image! (read-image rdr)))
如果相反,您的文件包含多个图像,而您需要跳过每个图像的第一行,则最好的方法是编写一个函数,将行的序列划分为一系列的图像(具体操作取决于文件格式),然后将其映射到(行序列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.带有 partition-into-individual-image-descriptions ,这将产生一个懒惰的seq懒惰序列.您需要先消耗它们,然后 with-open
关闭阅读器.
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.
这篇关于读取Clojure中的文件并忽略第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!