如何将文本转换为使用Kotlin分组的单词列表?
我有类似的字符串文本:
val text: String = "aa bb cc aa bb aa aa / <"
我首先尝试跳过特殊字符,例如&lt;*/&amp;^$
,然后将单词组成类似的对象单词列表:
data class Word(val id: Int, val text: String, val count: Int)
listOf(Word(1, aa, 4), Word(2, bb, 2), Word(3, cc, 1))
这是我的方法,但是它需要3个不好的循环加上锅炉板代码
val wordWithCountMap = mutableMapOf<String, Int>()
text.trim().split(" ").forEach { word ->
if (word.isNotEmpty() && word.isNotBlank()) {
val key = regex.replace(word, "")
wordWithCountMap[key] = wordWithCountMap[word]?.plus(1) ?: 1
}
}
val wordList = arrayListOf<Word>()
wordWithCountMap.onEachIndexed { index, entry ->
wordList.add(
Word(
id = index, text = entry.key,
count = entry.value
)
)
}
I have String text like that:
val text: String = "aa bb cc aa bb aa aa / <"
I am try first to skip special characters like <*/&^$
, then group words into list of object word like that:
data class Word(val id: Int, val text: String, val count: Int)
listOf(Word(1, aa, 4), Word(2, bb, 2), Word(3, cc, 1))
This is my approach but it requires 3 loops which is bad plus the boiler plate code
val wordWithCountMap = mutableMapOf<String, Int>()
text.trim().split(" ").forEach { word ->
if (word.isNotEmpty() && word.isNotBlank()) {
val key = regex.replace(word, "")
wordWithCountMap[key] = wordWithCountMap[word]?.plus(1) ?: 1
}
}
val wordList = arrayListOf<Word>()
wordWithCountMap.onEachIndexed { index, entry ->
wordList.add(
Word(
id = index, text = entry.key,
count = entry.value
)
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)