2011-02-11 156 views
1

我目前正在寫一個LISP程序,其分析CR結果列表的形式像以下: ( 「I」 0 10 0 20)< <(字X0 X1 Y0 Y1)Common Lisp的串聯和換行符

它必須使用單詞的位置來構建整個文本。 我的代碼有一個聚類分析器,可以找出像左對齊或右對齊或甚至兩者的段落。羣集數據結構如下所示: (「cluster name」xline y0 y1'(cluster words))

如何在我迭代字符串列表並將它們連接到結果字符串中時添加新行從這些創建一個格式化文本? 例子:

"Hi,\n 
\n 
here is my entry\n 
\n 
Good bye" 

我的代碼看起來如下:

(defun print-formatted-text(txt) 
    (let 
     ((size (array-total-size txt)) 
     (sorted (sort (sort txt #'compare-mix) #'compare-generic2)) 
     (result "")) 
    (loop for i from 0 to (1- size) do 
      (let ((el (aref sorted i))) 
      (if (word? el) 
       (setf result (concatenate 'string result (first el) " ")) 
       (if (null (nth 7 el)) 
        nil 
       (progn 
        (setf result (concatenate 'string result " ")) 
        (dolist (curr (nth 7 el)) 
        (setf result (concatenate 'string result (first curr) " ")))))))) 
    result)) 

如果目前的數據是不發一言,那麼它是一個段落。這意味着,我需要添加一個新的行,然後再給出段落的單詞。

在這裏恰當地使用連接嗎?

謝謝你的建議。

回答

6

我不能完全按照你的計劃,但它與字符串流,並使用formatwrite-stringwrite-lineterpri,以及相關的功能,例如更容易

(let ((lines '("Hi," "Here is my entry" "Good bye"))) 
    (with-output-to-string (stream) 
    (dolist (line lines) 
     (write-line line stream) 
     (terpri stream)))) 
=> 
"Hi, 

Here is my entry 

Good bye 

" 
2

有關編碼風格

(defun print-formatted-text(txt) 
    (let 
     ((size (array-total-size txt)) 
     (sorted (sort (sort txt #'compare-mix) #'compare-generic2)) 
     (result "")) 
    (loop for i from 0 to (1- size) do 
      (let ((el (aref sorted i))) 

(LOOP FOR e1 ACROSS一些東西整理

  (if (word? el) 
       (setf result (concatenate 'string result (first el) " ")) 

重複的字符串的串聯真的很浪費。正如Xach指出的,STREAMS是更好的抽象。

   (if (null (nth 7 el)) 
        nil 
       (progn 

使用:(when (nth 7 e1)

    (setf result (concatenate 'string result " ")) 
        (dolist (curr (nth 7 el)) 
        (setf result (concatenate 'string result (first curr) " ")))))))) 
    result)) 
1

如果您正在使用的字符或換行連擊,那麼你需要在括號包圍,以便它是一個列表,這樣'(#\Newline)

其中#\換行符是換行符。

需要將所有字符(如從字符串中提取的字符,如(elt "abc" 1))製成列表,如(list (elt "abc" 1)

例如代碼:

(concatenate 'string 
    "Hi ther" '(#\e) "." '(#\Newline) "How " (list #\a #\r #\e) " you!") 

=> "Hi there. 
How are you!"