gpt4 book ai didi

scala - 在元组中拆分字符串

转载 作者:行者123 更新时间:2023-12-03 23:58:05 25 4
gpt4 key购买 nike

在一个函数中 def a(l: List[(Int, String)]): List[(Int, String)] = ??? 我想把一个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))

关于scala - 在元组中拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67693738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com