【问题标题】:Clojure - read text file and enter it as a listClojure - 读取文本文件并将其作为列表输入
【发布时间】:2022-11-30 06:42:33
【问题描述】:

我在使用 Clojure 进行一些基本的 IO 操作时遇到了问题。我有一个需要阅读的文本文件,用“|”分隔字符,并输入列表以供以后处理。这是我的文本文件的内容:

1|John Smith|123 Here Street|456-4567 
2|Sue Jones|43 Rose Court Street|345-7867 
3|Fan Yuhong|165 Happy Lane|345-4533

这是我当前的代码:

((defn -main [] 
(println "Enter an option: \n")

(let [choice (read-line)]
  
  (cond (= choice "1") 
        (let [cust-contents (slurp "file.txt")
              nums-as-strings (clojure.string/split cust-contents #"|")
              numbers (map read-string nums-as-strings)]
              (print numbers)
        ) 
  )
) ) )


(-main)

我认为这段代码可以工作,但是这是我在运行程序时遇到的错误:

(; Execution error at user/eval7923$-main (REPL:11).
; EOF while reading

谁能指导我哪里出错以及如何解决这个问题?

【问题讨论】:

    标签: file clojure txt


    【解决方案1】:

    一方面,您不应该连续使用 2 个左括号,例如 ((defn ...

    此外,CSV 解析有许多库来消除重新发明轮子的苦差事。我最喜欢的如下图所示:

    (ns tst.demo.core
      (:use demo.core tupelo.core tupelo.test)
      (:require
        [tupelo.csv :as csv]))
    
    (verify
      ; ***** NOTE *****  most CSV has a header line, which is added below for convenience!
      (let [data-str "id|name|address|phone
                      1|John Smith|123 Here Street|456-4567
                      2|Sue Jones|43 Rose Court Street|345-7867
                      3|Fan Yuhong|165 Happy Lane|345-4533 "
            entity-maps (csv/csv->entities data-str {:separator |})]
        (is= entity-maps
          [{:address "123 Here Street", :id "1", :name "John Smith", :phone "456-4567"}
           {:address "43 Rose Court Street", :id "2", :name "Sue Jones", :phone "345-7867"}
           {:address "165 Happy Lane", :id "3", :name "Fan Yuhong", :phone "345-4533"}])))
    

    上面的解决方案基于my favorite template project,最后还有一个文档源列表。

    你可以找到检查tupelo.csv的源代码 还有the unit tests

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多