29 lines
948 B
Swift
29 lines
948 B
Swift
import Foundation
|
||
|
||
/// 文本后处理:保留系统标点,不清洗,只在缺少句末标点时补句号。
|
||
enum TextPostProcessor {
|
||
private static let terminalPunctuation: Set<Character> = [
|
||
"。", "!", "?", "…", ";", ":", ".", "!", "?", ";", ":", "\n"
|
||
]
|
||
|
||
private static let closingMarks: Set<Character> = ["”", "\"", "」", "』", ")", ")", "》", "】", "’", "'"]
|
||
|
||
static func finalize(_ raw: String, addPeriod: Bool) -> String {
|
||
var text = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
guard !text.isEmpty else { return "" }
|
||
|
||
guard addPeriod else { return text }
|
||
|
||
var probe = text
|
||
while let last = probe.last, closingMarks.contains(last) {
|
||
probe.removeLast()
|
||
}
|
||
guard let last = probe.last else { return text }
|
||
if !terminalPunctuation.contains(last) {
|
||
text += "。"
|
||
}
|
||
return text
|
||
}
|
||
|
||
}
|