我必须编写一个函数,给定一个文件名,指针和一个替换,它交换给定文本文档中的两个字符串。该函数必须使用System.IO.File.OpenText,WriteLine和ReadLine语法。我现在被困在这里,其中函数似乎覆盖给定的文本文档而不是替换针。
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
答案 0 :(得分:4)
您的代码的问题在于您在阅读lines
时使用了延迟序列。当您使用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
来电,因为use
会为您解决此问题。
编辑:我放回了所需的do
个关键字 - 我对您的格式感到困惑。大多数人会像在我的更新版本中那样在上一行的末尾写下它们。