【问题标题】:editing text in a file using racket使用球拍编辑文件中的文本
【发布时间】:2014-07-05 19:13:10
【问题描述】:

我有一个球拍程序(包括文件)的其他几个文件,其中一些文件包含我想使用主程序中的函数更新的球拍代码。 IE。这就是我要编辑的文件的样子(基本上)

(define somethings '(
        (some list)
        (some other list)
        (yet another list)))

我希望能够在列表中添加更多内容,我认为有更好的方法可以做到这一点,但由于我是新手,所以我首先尝试了:

(define (update-file arg1 arg2 arg3 . args)
    (call-with-output-file "somefile.rkt" #:exists 'append
       (lambda (output-port)
          (print "\b\b" output-port) ;; have tried several variations of this they all 
          (do other things)          ;; print the backspaces literally rather than 
          (display "))" output-port) ;; removing characters
          (newline output-port))))

我认为问题既是 A:我正在使用 append,它可能只是在最后粘贴东西(但更新和截断似乎不是答案)和 B:打印 \b 不能像我一样工作正在尝试使用它... :)

我现在正绝望地浏览 Racket 的文档,但我是编程新手,所以大部分内容还没有任何意义。是否有某种方法可以使该特定功能起作用,如果是的话,是否值得,或者是否有更好的方法来实现相同的结果?

非常感谢

【问题讨论】:

  • 以编程方式编辑 S 表达式的最佳方法是将其视为数据结构(通过reading 将其输入),更新它,然后将其写回(使用 write) ,而不是将其视为一串文本。
  • @ChrisJester-Young 啊,谢谢更好的主意。我不确定具体如何实现,但我会弄清楚的。

标签: text racket editing


【解决方案1】:

试试这个:

(call-with-input-file "somefile.rkt"
  (lambda (in)
    (let* ((input  (call-with-input-string (port->string in) read))
           (output (list (car input)  ; define
                         (cadr input) ; somethings
                         (list 'quote
                               (append
                                (car (cdaddr input))      ; old list
                                '((do other things))))))) ; new elements
      (call-with-output-file "somefile.rkt" #:exists 'replace
        (lambda (out)
          (write output out))))))

这是正在发生的事情:

  1. 首先,我们将read的内容"somefile.rkt"转换成一个名为input的变量,结果是一个S-Expressions列表
  2. 然后,按照 Chris 的建议,我们使用标准操作操作该列表,直到它具有所需的值
  3. 最后,我们write将结果返回到同一个文件中,覆盖之前的内容

最后,"somefile.rkt" 将包含以下文本:

(define somethings
  (quote
   ((some list)
    (some other list)
    (yet another list)
    (do other things))))

不用担心quote,这和写' 是一样的。唯一需要注意的是,文本的原始格式将丢失,所有内容都显示在一行中。

【讨论】:

  • 奥斯卡·洛佩兹 谢谢,那行得通。我以不同的方式解决了问题(因为我不知道如何处理定义)并将主文件中的变量定义为(read file-in)(文件输入为:(define file-in (open-input-file file.rkt)),并且只包含 file.txt引用的列表。我不确定哪个解决方案更灵活,但我可以漂亮地打印我的,所以它是可读的。我认为你的可能会进行一些修改。使用'replace 而不是'truncate 和(call-with-out-put-file) 有什么好处?
  • @user138888 好的!重要的是您了解解决方案的工作原理,无论您选择哪一个每个标志
猜你喜欢
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 2011-01-12
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 2017-07-04
相关资源
最近更新 更多