2013-04-18 63 views
2

所以我必須在Scheme中完成一個項目,並且我很困難。基本上,程序所做的是打開文件並輸出統計信息。現在我可以計算字符的數量,但我還需要計算行數和單詞的數量。我現在只是試圖解決這種情況,但最終我還得接受兩個文件 - 第一個文本文件就像一本書。第二個是單詞列表,我必須計算這些單詞出現在第一個文件中的次數。顯然,我將不得不與名單一起工作,但我會喜歡一些幫助。這裏是計劃幫助 - 文件統計

(define filestats 
      (lambda (srcf wordcount linecount charcount) 

       (if (eof-object? (peek-char srcf)) 
        (begin 
         (close-port srcf) 
         (display linecount) 
         (display " ") 
         (display wordcount) 
         (display " ") 
         (display charcount) 
         (newline)() 
        ) 
        (begin 
         (read-char srcf) 
         (filestats srcf 0 0 (+ charcount 1)) 
        ) 
       ) 

      ) 
) 

(define filestatistics 
    (lambda (src) 
    (let ((file (open-input-file src))) 
     (filestats file 0 0 0) 
    ) 
) 
) 
+0

[方案文件統計資料]的可能重複(http://stackoverflow.com/questions/16063788/file-stats-in-scheme) –

+0

否 '的括號掛着' 請;他們不是大括號。 – GoZoner

回答

0

如何將文件「標記化」爲行列表,其中行是單詞列表,單詞是字符列表。

(define (tokenize file) 
    (with-input-from-file file 
    (lambda() 
     (let reading ((lines '()) (words '()) (chars '())) 
     (let ((char (read-char))) 
      (if (eof-object? char) 
       (reverse lines) 
       (case char 
       ((#\newline) (reading (cons (reverse (cons (reverse chars) words)) lines) '() '())) 
       ((#\space) (reading lines (cons (reverse chars) words) '())) 
       (else  (reading lines words (cons char chars)))))))))) 

一旦你這樣做了,其餘的都是微不足道的。

> (tokenize "foo.data") 
(((#\a #\b #\c) (#\d #\e #\f)) 
((#\1 #\2 #\3) (#\x #\y #\z))) 
0

使用計劃字數算法之前已經在堆棧溢出here解釋,例如(向上滾動到頁面的最上方看到的是我到目前爲止(和作品)代碼用C等同程序):

(define (word-count input-port) 
    (let loop ((c (read-char input-port)) 
      (nl 0) 
      (nw 0) 
      (nc 0) 
      (state 'out)) 
    (cond ((eof-object? c) 
      (printf "nl: ~s, nw: ~s, nc: ~s\n" nl nw nc)) 
      ((char=? C#\newline) 
      (loop (read-char input-port) (add1 nl) nw (add1 nc) 'out)) 
      ((char-whitespace? c) 
      (loop (read-char input-port) nl nw (add1 nc) 'out)) 
      ((eq? state 'out) 
      (loop (read-char input-port) nl (add1 nw) (add1 nc) 'in)) 
      (else 
      (loop (read-char input-port) nl nw (add1 nc) state))))) 

程序接收輸入端口作爲參數,所以它可以應用它,比方說,一個文件。請注意,爲計算單詞和行數,您需要測試當前字符是新行字符還是空白字符。並且需要額外的標誌(在代碼中稱爲state)來跟蹤新單詞的開始/結束。