【问题标题】:Read a file in clojure and ignore the first line?在clojure中读取文件并忽略第一行?
【发布时间】:2013-10-01 13:24:09
【问题描述】:

使用this answer的代码,我有

(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”)作为第一行,我不需要这条线。我尝试了一些方法(保留索引、模式匹配),但我的方法感觉做作。

【问题讨论】:

    标签: text clojure functional-programming matching


    【解决方案1】:

    假设您想跳过文件的第一行并像在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)))
    

    如果您的文件包含多个图像并且您需要跳过每个图像的第一行,最好的方法是编写一个函数来将 seq 行划分为 seq 图像(如何完成取决于文件的格式),然后将其映射到 (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 关闭阅读器之前使用它们。

    【讨论】:

    • 为了澄清,每张图片都在一个单独的文件中。
    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 2020-11-03
    • 2021-07-29
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多