【问题标题】:how to read and parse contents of text file into a Dictionary in Swift(CreateML)如何在 Swift(CreateML) 中读取文本文件的内容并将其解析为字典
【发布时间】:2020-04-18 03:23:23
【问题描述】:

如何从文件中读取字典? 例如我的文本文件如下所示:

[“book": [-0.33568978, -0.42831486],...]

我想读它并放入字典

let myVector = [String:[Double]]()

【问题讨论】:

  • 你的意思是[String:[Double]]。这看起来像一个 JSON 字符串。看看JSONDecoder
  • 最难的部分是什么?展示一些代码并解释其中的难点。
  • 感谢@LeoDabus,这是一个很棒的提示!

标签: swift file dictionary createml


【解决方案1】:

这是我为尝试使用 CreateML 导入自己的自定义嵌入的其他人提供的解决方案。

import Foundation
import PlaygroundSupport
import CreateML

do {
    let fileUrl = PlaygroundSupport.playgroundSharedDataDirectory.appendingPathComponent("resultsmall.json")
    let data = try Data(contentsOf: fileUrl)
    let decoder = JSONDecoder()
    let json = try decoder.decode([String: [Double]].self, from: data)

    let embedding = try MLWordEmbedding(dictionary: json)
    try embedding.write(to: URL(fileURLWithPath: "~/Desktop/WordEmbedding.mlmodel"))

} catch {
    print(error)
}

【讨论】:

    猜你喜欢
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 2017-11-28
    • 2021-07-27
    • 1970-01-01
    相关资源
    最近更新 更多