add plain text parser with paragraph-based chapter splitting

This commit is contained in:
2026-03-13 21:52:42 +01:00
parent 2e647d7fe3
commit c753a3a147
2 changed files with 57 additions and 0 deletions
@@ -0,0 +1,21 @@
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)
}
}