Files
vorleser/VorleserKit/Sources/BookParser/PlainTextParser.swift
T

22 lines
706 B
Swift

import Foundation
public struct PlainTextParser {
public static func parse(text: String, title: String, author: String? = nil) -> Book {
let paragraphs = text.components(separatedBy: "\n\n")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
let chapters = paragraphs.enumerated().map { index, text in
Chapter(index: index, title: "Section \(index + 1)", text: text)
}
return Book(title: title, author: author, chapters: chapters)
}
public static func parse(url: URL) throws -> Book {
let text = try String(contentsOf: url, encoding: .utf8)
let title = url.deletingPathExtension().lastPathComponent
return parse(text: text, title: title)
}
}