2013-04-18 1 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라고 함)가 필요합니다.