字符串替换工具从Python转换为F#

2 投票
1 回答
603 浏览
提问于 2025-04-16 18:25

我有一段简单的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#实现的这个工具会是什么样子的呢?它能比这个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)

1 个回答

4

我不会给你一个完整的F#示例,因为我不太确定你在Python版本中使用的正则表达式是干什么的。不过,一个不错的F#解决方案的大致结构可能是这样的:

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)

因为你的代码是逐行处理的,所以我用了ReadAllLines来把文件读成一行一行的列表,然后用Seq.map对每一行应用一个函数。这样处理后的新行集合可以通过WriteAllLines写回文件。

正如评论中提到的,我觉得你在Python中也可以写出差不多的代码(也就是说,不需要明确地把字符串连接起来,而是可以使用一些更高级的函数或者理解语法来处理这个集合)。

撰写回答