F# 使用OpenText、ReadLine和WriteLine编写替换字符串的函数
我必须编写一个函数,给定文件名、指针和替换,在给定的文本文档中交换两个字符串。函数必须使用System.IO.File.OpenText、WriteLine和ReadLine语法。我现在被困在这里,函数似乎覆盖了给定的文本文档,而不是替换指针F# 使用OpenText、ReadLine和WriteLine编写替换字符串的函数,f#,F#,我必须编写一个函数,给定文件名、指针和替换,在给定的文本文档中交换两个字符串。函数必须使用System.IO.File.OpenText、WriteLine和ReadLine语法。我现在被困在这里,函数似乎覆盖了给定的文本文档,而不是替换指针 open System let fileReplace (filename : string) (needle : string) (replace : string) : unit = try // uses try-with to ca
open System
let fileReplace (filename : string) (needle : string) (replace : string) : unit =
try // uses try-with to catch fail-cases
let lines = seq {
use file = IO.File.OpenText filename // uses OpenText
while not file.EndOfStream // runs through the file
do yield file.ReadLine().Replace(needle, replace)
file.Close()
}
use writer = IO.File.CreateText filename // creates the file
for line in lines
do writer.Write line
with
_ -> failwith "Something went wrong opening this file" // uses failwith exception
let filename = @"C:\Users\....\abc.txt"
let needle = "string" // given string already appearing in the text
let replace = "string" // Whatever string that needs to be replaced
fileReplace filename needle replace
代码的问题是在读取行时使用了惰性序列。当您使用seq{..}时,直到需要时才会实际计算主体。在您的示例中,这是在for循环中对行进行迭代时,但在代码到达之前,您调用CreateText并覆盖该文件 您可以通过使用一个列表来修复此问题,该列表将立即进行评估。您还需要将Write替换为WriteLine,但其余的都可以
let fileReplace (filename : string) (needle : string) (replace : string) : unit =
try // uses try-with to catch fail-cases
let lines =
[ use file = IO.File.OpenText filename // uses OpenText
while not file.EndOfStream do // runs through the file
yield file.ReadLine().Replace(needle, replace)
]
use writer = IO.File.CreateText filename // creates the file
for line in lines do
writer.WriteLine line
with
_ -> failwith "Something went wrong opening this file" // uses failwith exception
我还删除了Close call,因为use会为您解决这个问题
编辑:我放回了所需的do关键字-我被你的格式弄糊涂了。大多数人会在前一行的末尾编写它们,就像在我的更新版本中一样。这不是实际问题,您提供了一些代码,您描述了一些您的问题,但我们仍然不知道应该怎么做。顺便说一句,这个网站是关于解决问题,但不是调试代码或为某人编写整个代码;我相信你需要做的是屈服,同时也要做的是理解-@s952163修复-我被OP的格式弄糊涂了!