add plain text parser with paragraph-based chapter splitting
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user