从列表中的字符串中替换/删除某些字符

0md85ypi  于 2021-07-14  发布在  Java
关注(0)|答案(3)|浏览(391)

我应该忽略列表中字符串中的所有“,”,“-”和“”。列表如下:例如: 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 "''" => ""
})
mrwjdhj3

mrwjdhj31#

一个简单的正则表达式和 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)
aydmsdu9

aydmsdu92#

你可以申请 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")
vltsax25

vltsax253#

基于regex的其他答案是可行的,但正如学习练习所指出的,我们可以将字符串概念化为字符序列,这意味着我们可以将它们视为集合,这样通常的可疑Map/过滤器等也可以工作

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

哪里

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

相关问题