clojure - 如何将这段文字解析成一棵树?

标签 clojure tree

我想获取文本(下面的示例)并将其转换为可以遍历的嵌套数据结构:

Arbirarchy !
  dog, my friend
    Bailey the Great
  cats, my enemies
    Robert the Terrible
    Trev the Diner
    Gombas the Tasty
      Lenny Lion
  Alligators
    Sadly I have none

最佳答案

这是解决方案吗?

(defn parse [s]
  {(re-find #"(?m)^.+" s)
   (map parse (map #(str/replace % #"(?m)^\s{2}" "")
                   (map first (re-seq #"(?m)(^\s{2}.+(\n\s{4}.+$)*)" s))))})

您的字符串(假设“Gombas”缩进):

(def s "hierarchy\n  dog\n    Bailey\n  cats\n    Robert\n    Trev\n    Gombas")

测试

(parse s)
-> {"hierarchy" ({"dog" ({"Bailey" ()})}
                 {"cats" ({"Robert" ()}
                          {"Trev" ()}
                          {"Gombas" ()})})}

关于clojure - 如何将这段文字解析成一棵树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13392545/

相关文章:

clojure - Clojure 中的解构函数参数

Clojure 线程在映射评估之间休眠

linux - 如何在 BeagleBone Black 上以非 root 用户身份获取启动时运行的命令?

html - 从 HTML 文档树打印 CSS 的算法

html - 如何在 HTML 中生成非常复杂的树结构

c - 二进制删除两个子案例

clojure - ClassCastException java.lang.Boolean 不能转换为 clojure.lang.IFn

clojure - 为什么 `core.async/pipeline` 返回一个 channel ?

RPART - 特征类型

c - 修复c中的树结构