在 kotlin 中初始化字典

发布于 2025-01-14 11:51:16 字数 316 浏览 0 评论 0原文

我怎样才能完成这段代码,以便我可以用我在另一个文件中编写的一些单词来初始化 Kotlin 中的字典?

val fisier= 文件("src/main/resources/Poveste_dictionar.txt") val Dictionar = hashMapOf(.........)

该文件如下所示: 曾经”到“Odata”, “在”到“ca”, “一”到“”, “时间”到“niciodata”, 从“那儿”到“阿科洛”, “是”到“福斯特”, “an”到“o”, “老”到“巴特拉纳”, “女人”到“femeie”,

How can I complete this code so I can initialize a dictionary in Kotlin with some words I wrote in another file?

val fisier= File("src/main/resources/Poveste_dictionar.txt")
val Dictionar = hashMapOf<String, String>(.........)

the file looks like that:
Once" to "Odata",
"upon" to "ca",
"a" to "",
"time" to "niciodata",
"there" to "acolo",
"was" to "a fost",
"an" to "o",
"old" to "batrana",
"woman" to "femeie",

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等往事风中吹 2025-01-21 11:51:16

假设您的文件如下所示:

"Once" to "Odata"
"upon" to "ca"
"time" to "niciodata"

您可以使用以下代码创建一个包含所有关联的映射:

val fileContent = this::class.java.getResource("dictionary.txt")?.readText() ?: throw FileNotFoundException() // read the file or throw exception if it doesn't exist
val words = fileContent
    .lines() // iterate over each line
    .associate { line ->
        val (first, second) = line.split(" to ") // extract the first and second word
        first.removeSurrounding("\"") to second.removeSurrounding("\"") // remove quotes and create a Pair
    }

println(words)

该代码片段会生成以下输出:

{Once=Odata, upon=ca, time=niciodata}

Assuming your file looks like this:

"Once" to "Odata"
"upon" to "ca"
"time" to "niciodata"

you can use the following code to create a map that contains all associations:

val fileContent = this::class.java.getResource("dictionary.txt")?.readText() ?: throw FileNotFoundException() // read the file or throw exception if it doesn't exist
val words = fileContent
    .lines() // iterate over each line
    .associate { line ->
        val (first, second) = line.split(" to ") // extract the first and second word
        first.removeSurrounding("\"") to second.removeSurrounding("\"") // remove quotes and create a Pair
    }

println(words)

That snippet produces the following output:

{Once=Odata, upon=ca, time=niciodata}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文