我已经学习了几天球拍,我对此任务感到困惑,我试图在文本文件中找到空行并选择一个随机空行来插入文本"在这里计算",这是迄今为止我已经得到的。
例如:myfile.txt包含以下内容:
line1
line2
line3
line4
运行脚本后,myfile.txt现在应该如下所示:
line1
calculation here
line2
line3
line4
或:
line1
line2
line3
calculation here
line4
下面的非工作代码:
#lang racket
(define (write-to-file host text) (
with-output-to-file host (
lambda () (
write text))
#:exists 'replace))
(define empty-lines '()) ;store line number of empty line (if any)
(define (file-lines text-file)
(file->lines text-file))
(define (add-to-list line-num)
(set! empty-lines (cons line-num empty-lines)))
(let loop ((l (file-lines "myfile.txt")))
(cond ((null? l) #f)
(else
(printf "~s\n" (first l)) ; just for debugging
(cond ((equal? (first l) "") (add-to-list (first l)))(else #f))
(loop (rest l)))))
;now i need to select a random line from the list of empty-lines.
;and write "calculations here" to that line
我正在使用的读取线方法没有问题,问题是检测并选择一个随机的空白空间来插入我的文本。
答案 0 :(得分:1)
(define (read-next-line-iter file)
(let ((line (read-line file)))
(unless (eof-object? line)
(display line)
(newline)
(read-next-line-iter file))))
(call-with-input-file "foobar.txt" read-next-line-iter)
http://rosettacode.org/wiki/Read_a_file_line_by_line#Racket
此功能可以帮助您逐行读取文件。 检查长度是否为0.并将该行替换为注释
答案 1 :(得分:0)
给定文件名,您可以使用file->lines
将其读入行列表。例如:
(for ([line (in-list (file->lines "some-file"))])
(displayln (cond [(zero? (string-length line)) (make-random-line)]
[else line])))
make-random-line
是某些函数,您定义为返回a
随机字符串,正如你所说的那样。
以上将整个文件读入内存中的列表。对于较大的文件,最好逐行处理。您可以使用in-lines
序列执行此操作:
(with-input-from-file "some-file"
(thunk
(for ([line (in-lines)])
(displayln (cond [(zero? (string-length line)) (make-random-line)]
[else line])))))
现在我理解你的问题了:
#lang racket
(define lines (file->lines "some-file-name"))
(define empty-line-numbers (for/list ([line (in-list lines)]
[n (in-naturals)]
#:when (zero? (string-length line)))
n))
(define random-line-number (list-ref empty-line-numbers
(random (length empty-line-numbers))))
(for ([line (in-list lines)]
[n (in-naturals)])
(displayln (cond [(= n random-line-number) "SOME NEW STRING"]
[else line])))
答案 2 :(得分:-1)
在文件中查找2个并发\ n。我很确定球拍有这样做的方法。将这些索引存储在列表中随机选择一对并将第二个\ n替换为"此处计算\ n"。