带#'匹配的F#功能'和'查找和替换'

时间:2013-03-18 21:48:33

标签: f# match replace

我正在努力创建一个F#函数。我是F#的新手(充其量)并且真的可以使用一些帮助。我已经倾倒了一个星期,所以你能提供的任何帮助都是非常宝贵的!


功能目标:

  • 输入:Liststring
  • 将字符串修改为Proper Case
  • 将字符串与列表中的每个项目进行比较
  • 用列表项替换任何匹配的项目

示例:

  • String =“美元在sc”
  • List = [“NIF”; “PF”; “PS”; “SC”; “我们”; “美国”; “USD”]

功能操作:

  1. 将字符串设置为Proper Case =“美元在sc中”
  2. 将字符串与列表中的每个项目进行比较,并根据需要进行替换
    • “我们”变成“美国”
    • “sc”变为“SC”
  3. 最终结果是“美元在南卡罗来纳州”
  4. 这就是我到目前为止所做的。

    let myList = ["NIF"; "PF"; "PS"; "SC"; "US"; "USA"; "USD"]
    let FixAccronyms aList fixString= 
        aList |> List.iter 
            (fun listItem ->
            match listItem with            
            | fixString -> printfn  "%s, %s" listItem fixString
            | _ ->  printf  "%s" "" |> ignore)
    

    在FSI:

      

    FixAccronyms myList“美元在sc中”;;

    该函数遍历列表,但它会打印列表中的每个项目,而不仅仅是它与fixString匹配的位置。假设有效,我既不确定如何模式匹配字符串的一部分,也不确定字符串中的查找和替换......


    FSI的结果

    val myList2 : string list = ["NIF"; "PF"; "PS"; "SC"; "US"; "USA"; "USD"]
    val FixAccronyms2 : aList:string list -> fixString:'a -> unit
    
    >FixAccronyms2 myList2 "the us dollar in sc";;
    NIF, NIF
    PF, PF
    PS, PS
    SC, SC
    US, US
    USA, USA
    USD, USD
    val it : unit = ()
    

    提前谢谢!

2 个答案:

答案 0 :(得分:1)

以这种方式:

open System
open System.Collections.Generic

let properCase lookup (str: string) =
  let lookupDict = Dictionary(StringComparer.CurrentCultureIgnoreCase)
  for word in lookup do lookupDict.Add(word, word)
  (str, str.Split()) ||> Array.fold (fun pcWord word -> 
    match lookupDict.TryGetValue(word) with
    | true, s -> pcWord.Replace(word, s)
    | _ -> pcWord)

> properCase ["NIF"; "PF"; "PS"; "SC"; "US"; "USA"; "USD"] "The us dollar in sc"
val it : string = "The US dollar in SC"

答案 1 :(得分:1)

这是另一种方法:

open System
open System.Text.RegularExpressions

let properCase lookup str =
    Regex.Replace(str, String.Join("|", Seq.map Regex.Escape lookup),
        (fun (x : Match) -> x.Value.ToUpper()),
        RegexOptions.IgnoreCase)

用法与@ Daniel的答案相同。