String Replace Utility Conversion From Python To F#
I have a simple python utility code that modifies the string line by line. The code is as follows. import re res = '' with open('tclscript.do','r') as f: lines = f.readlines(
Solution 1:
I will not give you a complete example of the F# version, because I'm not sure what the regular expression in your Python version is supposed to do. However, the general structure of a nice F# solution would look something like this:
let lines =
File.ReadAllLines("tclscript.do")
|> Seq.map (fun line ->
let newLine = line.Replace("{", "{{").Replace("}", "}}")
// Implement additional string processing here
newLine )
File.WriteAllLines("tclscript.txt", lines)
Since your snippet is working line-by-line, I used ReadAllLines
to read file as a list of lines and then used Seq.map
to apply a function to every line. The new collection of lines can be written to a file using WriteAllLines
.
As mentioned in the comment, I think that you can write pretty much the same thing in Python (i.e. without explicitly concatenating the string and using some higher-order function or comprehension syntax to process the collection).
Post a Comment for "String Replace Utility Conversion From Python To F#"