2

我有一个 txt 文件“blah.txt”,内容为

word 3 + 6

现在考虑以下代码:

(define c (read-char file))
(define (toke c)
        (cond
         ((null? c)(write "empty"))

        ((equal? (read-char c) #\space)(write 'space)
         ;           (toke (with the next character)
         )
         ((equal? (read-char c) #\+) (write '+)
          ;              (toke (with the next character)
         )
        ((equal? (read-char c) #\-) (write '-)
          ;               (toke (with the next character)
         )
         ((equal? (read-char c) #\*) (write '*)
          ;               (toke (with the next character)
         )
         ((equal? (read-char c) #\/) (write '/)
          ;               (toke (with the next character)
         )
         ((equal? (read-char c) #\=) (write '=)
          ;               (toke (with the next character)
           )           
         ((equal? (read-char c) #\() (write 'LPAREN)
            ;             (toke (with the next character)
         )
         ((equal? (read-char c) #\)) (write 'RPAREN)
          ;               (toke (with the next character)
         )
         ((char-numeric? (read-char c)) (write 'Num)
          ;                  (toke (with the next character)
         )

         ((char-alphabetic? (read-char c))(write 'ID)
          ;                    (toke (with the next character)
         )
         (else
          (write "error"))))

我不希望输出到文本文件。我只是希望能够继续下一个角色。我曾尝试解决它不成功。另外由于某种原因,我不断收到字符数字错误?和字符字母?告诉我,当我将文件另存为 3 a + r 时,我给了它 eof 而不是它所期望的(例如)

我知道这涉及将其更改为字符串,但我不断收到一串“单词 3 + 6”,但我无法做到(汽车)。让我再解释一下,我知道你可以做 (define list file->list "blah.txt") 将包含 '(word 3 + 4) 但然后做 (define str file->string "blah.txt" )它将包含“word 3 + 4”,我不能(car str)将“word”取出,因为整个(car)是“word 3 + 4”,如果我不能正确解释自己,请原谅我,因为我我是新来的计划

4

3 回答 3

1

使用 读取文件的内容(file->lines "blah.txt"),这将返回一个列表,文件的每一行都作为列表中的字符串。

之后,操作每一行就很简单了;例如,使用该过程string->list(请参阅文档cdr)将一行转换为字符列表,并通过对列表进行 -ing迭代每个字符。

于 2012-05-06T23:37:42.660 回答
1

Racket(更一般地说,Scheme)提供了一种端口数据类型,允许您顺序访问文件或流。您可以从中窥视读取单个字节。

这里有一些参考 Racket 文档:Byte and String input

作为这种扫描仪的一个示例,您可以查看我的关于制作基于 Racket 的语言的迷你教程的第 6 节。

请注意,字符串本身不是端口,但我们可以创建一个源来自字符串的端口。Racket 提供了open-input-string将字符串转换为输入端口的功能。所以你应该能够做这样的事情:

#lang racket
(define myport (open-input-string "hello"))

(printf "I see: ~s\n" (read-char myport))
(printf "I see: ~s\n" (read-char myport))
(printf "I see: ~s\n" (read-char myport))
(printf "I see: ~s\n" (read-char myport))
(printf "I see: ~s\n" (read-char myport))

看到个别字符出来。更改read-charpeek-char,您会看到它peek-char不会将数据带出端口,但允许您窥视它。

于 2012-05-07T23:22:59.707 回答
0

我建议阅读一些关于如何在 Scheme 中实现扫描仪的内容。Eric Hilsdale 和 Christopher T. Haynes 写了一些很好的笔记。

首先是扫描仪: http ://www.cs.indiana.edu/eip/compile/scanparse.html

然后是大图: http ://www.cs.indiana.edu/eip/compile/

于 2012-05-07T06:46:35.967 回答