我有一个简单的 python 实用程序代码,可以逐行修改字符串。代码如下。
import re
res = ""
with open("tclscript.do","r") as f:
lines = f.readlines()
for l in lines:
l = l.rstrip()
l = l.replace("{","{{")
l = l.replace("}","}}")
l = re.sub(r'#(\d+)', r'{\1}',l)
l += r'\n'
res += l
res = "code="+res
with open("tclscript.txt","w") as f:
f.write(res)
用 F# 实现的实用程序会是什么样子?它的 LOC 可以比这个 Python 版本更短、更容易阅读吗?
添加
python 代码处理 C# 字符串中的 tcl 脚本。C#字符串中的'{'/'}'应改为'{{'/'}}','#'后面的数字应修改为'{}'括起来的数字。例如,#1 -> {1}。
添加
这是工作示例
open System.IO
open System.Text.RegularExpressions
let lines =
File.ReadAllLines("tclscript.do")
|> Seq.map (fun line ->
let newLine = Regex.Replace(line.Replace("{", "{{").Replace("}", "}}"), @"#(\d+)", "{$1}") + @"\n"
newLine )
let concatenatedLine = Seq.toArray lines |> String.concat ""
File.WriteAllText("tclscript.txt", concatenatedLine)
或如本答案中所述。
open System.IO
open System.Text
let lines =
let re = System.Text.RegularExpressions.Regex(@"#(\d+)")
[|for line in File.ReadAllLines("tclscript.do") ->
re.Replace(line.Replace("{", "{{").Replace("}", "}}").Trim(), "$1", 1) + @"\n"|]
let concatenatedLine = lines |> String.concat ""
File.WriteAllText("tclscript.txt", concatenatedLine)