【问题标题】:How to chain operations in idiomatic scala如何在惯用的scala中链接操作
【发布时间】:2016-10-24 00:10:46
【问题描述】:

我想将正则表达式列表应用于字符串。我目前的方法不是很实用

我当前的代码:

  val stopWords = List[String](
    "the",
    "restaurant",
    "bar",
    "[^a-zA-Z -]"
  )

  def CanonicalName(name: String): String = {
    var nameM = name        
    for (reg <- stopWords) {
      nameM = nameM.replaceAll(reg, "")
    }

    nameM = nameM.replaceAll(" +", " ").trim
    return nameM
  }

【问题讨论】:

标签: scala functional-programming


【解决方案1】:

我认为这可以满足您的需求。

def CanonicalName(name: String): String = {
  val stopWords = List("the", "restaurant", "bar", "[^a-zA-Z -]")
  stopWords.foldLeft(name)(_.replaceAll(_, "")).replaceAll(" +"," ").trim
}

【讨论】:

    【解决方案2】:

    'replaceAll' 可以替换单词的一部分,例如:“the thermo & BBQ restaurant”被替换为“rmal becue”。如果您想要的是“热烧烤”,您可以先拆分名称,然后逐字应用您的停用词规则:

    def isStopWord(word: String): Boolean = stopWords.exists(word.matches)
    
    def CanonicalName(name: String): String = 
        name.replaceAll(" +", " ").trim.split(" ").flatMap(n => if (isStopWord(n)) List() else List(n)).mkString(" ")
    

    【讨论】:

      猜你喜欢
      • 2019-08-31
      • 2013-04-03
      • 2022-01-01
      • 2016-07-24
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 2018-06-04
      • 2011-07-17
      相关资源
      最近更新 更多