在元组中拆分字符串
在一个函数中,def a(l: List[(Int, String)]): List[(Int, String)] = ???我想将一个字符串拆分成小写的单词。逗号等应该被忽略,所以我想我需要replaceAll("[^A-Za-z]+", " ").toLowerCase()某个地方?Int 值应与句子中的值保持一致。
示例它应该如何工作:
val example = List((11, "That is great!"), (12, "Wow, impossible!"))
print(a(example))
结果
List((11, "that"),(11, "is"),(11, "great"),(12, "wow"),(12, "impossible"))
回答
你可以使用flatMap:
val example = List((11, "That is great!"), (12, "Wow, impossible!"))
example.flatMap { case (int, str) =>
str
.replaceAll("[^A-Za-z]+", " ")
.toLowerCase()
.split(' ')
.map((int, _))
}
产量:
res0: List[(Int, String)] = List((11,that), (11,is), (11,great), (12,wow), (12,impossible))