【问题标题】:Replacing/deleting some characters from a string which is in a List从列表中的字符串替换/删除某些字符
【发布时间】:2021-07-16 01:28:02
【问题描述】:

我应该忽略 List 中字符串中的所有 ","、"."、"-" 和 "" "。 列表是这样的:例如:List("This is an exercise, which I have problem with", "and I don't know, how to do it., "text-,.")

我刚刚尝试的是 map,但它不想编译。我也想使用replace,但决定不这样做,因为我应该为我想忽略的每个字符创建replace,例如replace(",", "").replace(".", "") 等等,不是吗? 也许有一种方法可以将我想忽略的所有字符放在一起?

我的代码:

val lines = io.Source.fromResource("ogniem-i-mieczem.txt").getLines.toList
println(lines.map{
    case "," => ""
    case "." => ""
    case "-" => ""
    case "''" => ""
})

【问题讨论】:

    标签: scala functional-programming


    【解决方案1】:

    您可以对其应用regex 并一次性替换它们。像这样:

    import scala.util.matching.Regex
    
    val regex = "\\.*,*-*\"*".r
    
    val sampleText = "Hi there. This comma, should be gone. and dots and quotes \"as well."
    val result = regex.replaceAllIn(sampleText, "")
    
    println(s"result: $result")
    // result: Hi there This comma should be gone and dots and quotes as well
    

    应用于您的示例代码,它可能如下所示:

    import scala.util.matching.Regex
    
    val regex = "\\.*,*-*\"*".r
    
    val result = io.Source
      .fromResource("ogniem-i-mieczem.txt")
      .getLines
      .toList
      .map { line => regex.replaceAllIn(line, "") }
    
    println(s"Result: $result")
    

    【讨论】:

      【解决方案2】:

      一个简单的正则表达式和replaceAllIn() 应该可以做到。

      val inLst =
        List("This is an exercise, which I have problem with"
           , "and I don't know, how to do it."
           , "text-,.")
      
      inLst.map("[-,.\"]".r.replaceAllIn(_, ""))
      //res0: List[String] = 
      // List(This is an exercise which I have problem with
      //    , and I don't know how to do it
      //    , text)
      

      【讨论】:

        【解决方案3】:

        其他基于正则表达式的答案是可行的方法,但就像学习练习一样,我们可以将字符串概念化为字符序列,这意味着我们可以将它们视为集合,因此通常的嫌疑人映射/过滤器等也可以工作

        lines map { _.filterNot { exclusionList.contains } }
        

        在哪里

        val exclusionList = Set(',', '.', '-', '"')
        

        【讨论】:

        • 次要提示,排除列表应为Set 以提高性能。 - 尽管正则表达式的性能更好:鬼脸:
        • 在这个答案中是否有理由使用{} 而不是更标准的()
        • @Tim 使用无标点符号docs.scala-lang.org/style/… 时只是一种微妙的文体效果。否则你可能会在( 之后出现空格,感觉很破旧。
        • 我设法做到了:val linesToHisto = lines.map(line => line.replaceAll("[.,:-]", "").replace(" ", "")) 我进行了第二次替换,因为我不知道如何在 replaceAll 中为正则表达式添加空间
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-16
        • 2018-11-03
        • 1970-01-01
        • 2018-08-23
        • 1970-01-01
        • 2014-10-09
        相关资源
        最近更新 更多