跳轉到內容

用 Leaf 程式設計 AI/與外部程式通訊

來自 Wikibooks,開放世界中的開放書籍

讓 Leaf 與其他程式交換資料可能很困難。本文作者 Thomas Messerschmidt 與他的機器人 Robot Betty9(參見 http://www.myspace.com/robotbetty9)一起建立了一種非常簡單但非常有效的方法,使 Leaf 可以與幾乎任何外部(對 LISP 而言外部)程式進行通訊。

該方法包括透過建立和銷燬小型文字 (.txt) 檔案在 Leaf/LISP 和外部世界之間傳遞文字訊息。它最初是為了讓 Leaf 使用標準的 ALICE-BASED(ProgramD)聊天機器人擴充套件其 AI 而編寫的。

第一部分包括函式 “sendchatout2chatbot”。它將資料寫入名為 “in.txt” 的“in” 檔案中。

第二部分包括函式 “readchatbotfile”。它讀取來自應用程式(在本例中為使用名為 “out.txt” 的檔案的聊天機器人)的返回文字。

聊天機器人介面程式碼開始 -----------------------------------------
聊天機器人介面程式碼開始 -----------------------------------------
聊天機器人介面程式碼開始 -----------------------------------------
程式碼作者:Thomas Messerschmidt(請註明作者。連結回 Betty9 會很好。)

(defun sendchatout2chatbot ()

 (print *text-phrase*)
       (setf mytext *text-phrase* )
       (setf mytext (subseq mytext 6))
       (with-open-file 
           (textin "C:/in.txt" :direction :output
                                        :if-exists :supersede)
           (print mytext textin)
       )
       (setf *text-phrase* nil)  )

(defun readchatbotfile ()

(with-open-file (stream "C:/out.txt")
  (do ((line (read-line stream nil)
              (read-line stream nil)))
   ((null line))
   (setf x1 line))) 
   (sapi-tts x1)
   (delete-file "C:/out.txt")   ); and then delete the file

(defun getchatin () ; tts 返回的聊天機器人內容,然後刪除檔案

 (if (probe-file "C:/out.txt") (readchatbotfile))  ) ; Read the file if there is a file to be read.


聊天機器人介面程式碼結束 -------------------------------------------
聊天機器人介面程式碼結束 -------------------------------------------
聊天機器人介面程式碼結束 -------------------------------------------


總結一下:1. 使用者向 Leaf 提問 2. Leaf 透過 sendchatout2chatbot 函式將問題傳送給聊天機器人,該函式寫入 “C:/in.txt” 3. 聊天機器人讀取 “C:/in.txt” 中提出的問題,然後刪除該檔案。4. 聊天機器人將對問題的回答寫入檔案 “C:/out.txt” 5. 當 Leaf 看到存在 C:/out.txt 檔案時,它會使用 readchatbotfile 函式讀取該檔案,該函式還使用 Microsoft 標準的 TTS(文字轉語音)SAPI 5.x 將其朗讀出來。6. Leaf 隨後刪除檔案 “C:/out.txt”。

華夏公益教科書