我正在尝试从文本文件导入数据。我可以读取文件,但我不知道如何将 String
解析为其他内容,例如元组。
文件 (text.txt
) 中的数据被格式化为像素及其颜色
(((0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0)),((63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479))
到目前为止,这是我的代码:
//
// ViewController.swift
import Cocoa
class ViewController: NSViewController {
@IBAction func passPix(_ sender: Any) {
let fileURL = "/Users/IMac/Desktop/text.txt"
var inString = ("Pix+Col")
do {
inString = try String(contentsOfFile: fileURL, encoding:String.Encoding.utf8)
} catch let error as NSError {
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
print(inString)
}
}
最佳答案
这是我的看法。基本上,您将原始字符串中的圆括号替换为方括号,将其转换为 JSON 对象,然后按照您认为合适的方式遍历生成的 JSON 对象:
let s = "(((0, 0), (1, 0), (2, 0), (3, 0), (4, 0)),((63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479)))"
var js = String(s.characters.map { $0 == "(" ? "[" : $0 })
js = String(js.characters.map { $0 == ")" ? "]" : $0 })
var data = js.data(using: .utf8)
let json = try! JSONSerialization.jsonObject(with: data!) as! [Any]
let coords = json[0] as! [Any]
let rgbs = json[1] as! [Any]
for (i, coord) in coords.enumerated() {
print ("\(coord) - \(rgbs[i])")
}
输出将是这样的:
[0, 0] - [63479, 62451, 63479]
[1, 0] - [63479, 62451, 63479]
[2, 0] - [63479, 62451, 63479]
[3, 0] - [63479, 62451, 63479]
[4, 0] - [63479, 62451, 63479]
因此,在每次迭代中,您将获得一个包含 x、y 坐标的数组和另一个包含像素的 r、g、b 颜色值的数组。您可以轻松地将它们转换为元组,但我认为此时没有必要这样做。
关于swift - 字符串到元组swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40446883/