【问题标题】:How to parse txt to list as symbols in Clojure? [closed]如何将 txt 解析为 Clojure 中的符号? [关闭]
【发布时间】:2018-03-14 14:56:45
【问题描述】:

我还是 Clojure 的新手;我正在尝试拆分从 txt 文件中解析的值,

我需要将这些单词作为 sembol 添加到列表中。例如

示例 txt 文件:

这是一个简单的测试

结果应该如下:

'((t h i s) (i s) (a) (s i m p l e) (t e s t)

请帮忙,在此先感谢。

【问题讨论】:

  • 请停止破坏您的问题。这不是本网站的运作方式。
  • 您要求的是 Clojure 代码,而不是 Python 代码。既然有了答案,就编辑您的问题以询问有关 Python 的问题没有帮助。

标签: clojure


【解决方案1】:

首先,您需要调用split 来获取字符串的单词。然后,对于每个单词,您需要迭代并将字符转换为符号。使用for 宏进行迭代是最容易的。您可以使用str 将字符转换为字符串,并使用symbol 将字符串转换为符号。

(defn line-to-lists [line]
  (for [word (clojure.string/split (clojure.string/trim line) #"\s+")]
    (for [char word] (symbol (str char)))))

(line-to-lists "this is a simple test")

您可以使用slurp 获取文件的内容并对其调用函数,如下所示:

(line-to-lists (slurp "file.txt"))

编辑:固定使用多个空格和尾随/前导空格。 编辑:添加字符串/修剪以删除不必要的白页。

【讨论】:

  • 多个空格失败: (line-to-lists "asd{three-spaces}asd") => ((asd) () () () (asd)) 和尾随空格例如
  • @leetwinski 谢谢,已修复!
  • 前导空格仍然失败:(line-to-lists "asd") => (() (a s d)) .. sorry :)
【解决方案2】:

首先你需要将一行分成单词, 然后每个单词都应该用char->symbol转换函数映射:

类似这样的:

user> (require '[clojure.string :as cs])
nil

user> (defn to-syms [s]
        (let [words (cs/split (cs/trim s) #"\s+")]
          (map #(map (comp symbol str) %) words)))
#'user/to-syms

user> (to-syms "this is a line")
;;=> ((t h i s) (i s) (a) (l i n e))

更新

扩展:

首先你从字符串中获取所有单词,用空格分隔:

(cs/split (cs/trim "aaa  bbb  ccc") #"\s+")
;;=> ["aaa" "bbb" "ccc"]

然后我们需要编写一个函数来处理单词并将其转换为符号列表。由于clojure字符串是一个字符序列,你可以map覆盖它,产生新的集合:

(defn char->sym [c]
  (symbol (string c))

user> (char->sym \a)
;;=> a

user> (map char->sym "asd")
;;=> (a s d)
;; in my example i use the functional composition: (comp symbol str)
;; that creates the function that works exactly like char->sym

;; let's wrap this mapping to a function:
(defn word->syms [w]
   (map char->sym w))

user> (word->syms "asd")
;;=> (a s d)

;; and now we just have to transform the whole list of words:
user> (map word->syms ["asd" "fgh"])
;;=> ((a s d) (f g h))

此外,要将符号列表转换为返回字符串,您可以简单地调用 str 函数,并将所有列表项作为参数 (apply str '(a s d)) => "asd",或使用 clojure.string/join(clojure.string/join '(a s d)) => "asd"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-17
    • 2012-02-10
    • 2019-09-05
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多