swift 文本文件格式的快速转换(字符串解析)

6ioyuze2  于 2023-02-07  发布在  Swift
关注(0)|答案(1)|浏览(216)

我想知道什么是最好的方法来获取包含以下格式行的文本文件:姓:名:猫的数量:狗的数量:鱼的数量:其他宠物的数量
并生成包含以下格式行的文本文件:

名字姓氏:宠物总数

例如,它将使用包含以下内容的文本文件:

Apple:Tim:0:0:3:0
Jobs:Steve:0:0:5:2
Da Kid:Billie:0:1:0:1
White:Walter:2:1:1:0
Bond:James:2:2:3:0
Stark:Tony:0:1:2:0
Wayne:Bruce:0:0:0:0

并输出一个文本文件,如下所示:

Tim Apple:3
Steve Jobs:7
Bille Da Kid:2
Walter White:4
James Bond:7
Tony Stark:3
Bruce Wayne:0

以下是我一直在尝试但没有成功的方法:

let namesFile = "Names"
let dir = try? FileManager.default.url(for: .documentDirectory,
      in: .userDomainMask, appropriateFor: nil, create: true)

// If the directory was found, we write a file to it and read it back
if let fileURL = dir?.appendingPathComponent(namesFile).appendingPathExtension("txt") {
    print (fileURL)

    var petSum = 0;
    do {
        let entriesString = try String(contentsOf: fileURL)

        let entries = entriesString.components(separatedBy: "\n")

        for entry in entries {
            let namePets = entry.components(separatedBy: ":")

            if (namePets.indices.contains(1)) {
                var sum = 0;

                print(namePets[1])
                print(namePets[0])

                for namePet in namePets {
                    if let intArg = Int(namePet) {
                        sum = sum + intArg
                    }
                }
                print (sum)
                print ("\n")
            }
        }

    } catch {
        print("Failed reading from URL, Error: " + error.localizedDescription)
    }
}
else {
    print("didn't work")
}

/*
 // Read from the file
 var inString = ""
 // Write to the file named Test
 let outString = "Write this text to the file"
 do {
     try outString.write(to: fileURL, atomically: true, encoding: .utf8)
 } catch {
     print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
 }

 */

会很感激任何帮助,谢谢!

6rqinv9w

6rqinv9w1#

  • 将文本拆分为行。
  • Map每条线
  • 将行拆分为以冒号分隔的组成部分。
  • 将场2到end转换为Int,并将它们相加。
  • 以新格式返回字符串。
  • 加入结果。
let text = """
Apple:Tim:0:0:3:0
Jobs:Steve:0:0:5:2
Da Kid:Billie:0:1:0:1
White:Walter:2:1:1:0
Bond:James:2:2:3:0
Stark:Tony:0:1:2:0
Wayne:Bruce:0:0:0:0
"""

let lines = text.components(separatedBy: .newlines)
let convertedLines = lines.map { line in
    let components = line.components(separatedBy: ":")
    return "\(components[1]) \(components[0]):\(components[2...].compactMap(Int.init).reduce(0, +))"
}
let result = convertedLines.joined(separator: "\n")

相关问题