【问题标题】:Parse HTML and build a map from the parsed value using clojure解析 HTML 并使用 clojure 从解析值构建映射
【发布时间】:2015-12-27 23:49:16
【问题描述】:

我正在使用 enlive clojure 来解析 HTML。我的解析器看起来像;

(def each-rows
  (for [tr crawl-page
        :let [row (html/select tr [:td (attr= :class "bl_12")])]
        :when (seq row)]
    row))

提取结果如下;

  {:tag :a,
   :attrs
   {:class "bl_12",
    :href
    "url1"},
   :content ("Chapter 1")}
  {:tag :a,
   :attrs
   {:class "bl_12",
    :href
    "url2"},
   :content ("Chapter 2")}
  {:tag :a,
   :attrs
   {:class "bl_12",
    :href
    "url3"},
   :content ("Chapter 3")}

现在我的目标是得到一本这样的字典;

   {:Chapter_1 "url1"  
   :Chapter_2 "url2"
   :Chapter_3 "url3"}

我设法编写了一个仅提取 href 或仅内容的方法,但无法将其作为地图

 (defn read-specific-other [x]
  (map (comp second :attrs) x))

输出:[:href "url1"]

  (defn read-specific-content [x]
    (map (comp first ::content) x))

(map read-specific-content each-rows)

输出:

(("Chapter 1"
"Chapter 2"
"Chapter 3"
))

如何获得想要的结果

【问题讨论】:

  • 您好,我正在考虑使用 Clojure 解析 XML。您选择 Clojure 是因为 (a) 它更高效还是 (b) 它是您刚刚使用的语言?

标签: html clojure


【解决方案1】:

看看zipmap

(zipmap (read-specific-other each-rows) (read-specific-content each-rows))

如果你真的希望键是关键字,那么使用keyword函数;但我建议保留字符串作为键。

还可以考虑改用into for 模式:

(into {}
  (for [[{:keys [attrs]} {:keys [content]}] rows]
    [content attrs]))

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 2017-07-02
    • 2017-07-18
    • 2016-09-26
    • 1970-01-01
    • 2013-06-24
    • 2019-10-02
    • 1970-01-01
    相关资源
    最近更新 更多