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

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/

10-09 03:04