如何修改Clojure代码实现指定格式的文件内容输出?
Solution to Adjust Your Clojure Code
Let's break down how to modify your code to get the exact output you want:
Key Changes Needed
Your current code uses the 0-based line index as the "ID", but you need to either:
- Use the original ID from each line (and sort by it), or
- Assign a new sequential ID starting at 1 (ignoring the original line ID)
Based on your desired output example, it looks like you want to use the original ID from each line. Here's how to do that:
Modified Code for Data Structure (Sorted by Original ID)
(->> (line-seq (clojure.java.io/reader "test.txt")) (map #(vec (.split % #"\|"))) ; Split each line into [ID, Name, Country, Phone] (map (fn [parts] [(Integer/parseInt (first parts)) ; Convert string ID to integer (vec (rest parts))])) ; Keep everything except the original ID (sort-by first)) ; Sort entries by the ID
This will produce a sorted sequence like:
([1 ["Austin" "Germany" "34-554567"]] [2 ["Mary Jane" "Australia" "45-78647"]] [3 ["King Kong" "New-Zealand" "35-467533"]])
If You Want the Exact String Format
To get the output as a string matching your desired example:
(clojure.string/join " " (map (fn [[id vals]] (str id ":[" (clojure.string/join " " (map #(str "\"" % "\"") vals)) "]")) (->> (line-seq (clojure.java.io/reader "test.txt")) (map #(vec (.split % #"\|"))) (map (fn [parts] [(Integer/parseInt (first parts)) (vec (rest parts))])) (sort-by first))))
This will output:
1:["Austin" "Germany" "34-554567"] 2:["Mary Jane" "Australia" "45-78647"] 3:["King Kong" "New-Zealand" "35-467533"]
Alternative: Sequential IDs Starting at 1 (Ignore Original ID)
If you want to ignore the original line IDs and assign a new sequential ID starting at 1:
(->> (line-seq (clojure.java.io/reader "test.txt")) (map #(vec (.split % #"\|"))) (map #(vec (rest %))) ; Drop original ID from data (map-indexed (fn [idx vals] [(inc idx) vals])) ; Assign 1-based sequential ID (sort-by first)) ; Sort by the new ID (which matches line order)
Explanation of Changes
- Replace Index with Original ID: Instead of using
map-indexedfor IDs, we extract the first element of each split line and convert it to an integer (so sorting works correctly). - Trim Unwanted Data: We use
(rest parts)to keep only the name, country, and phone number. - Sort:
sort-by firstensures the entries are ordered by ID as requested. - String Formatting: For the exact string output, we use
clojure.string/joinandstrto format each entry into the desiredID:[...]structure.
内容的提问来源于stack exchange,提问作者Prishu
相关产品推荐
相关产品推荐

