Swift:将字符串拆分成句子

arn*_*app 1 iphone ios swift

我想知道如何将包含多个句子的字符串拆分为句子数组。

我知道 split 函数,但 split by"."并不适合所有情况。

这个答案中是否有类似的内容

Pau*_*l B 5

如果您能够使用 Apple 的解决方案Foundation,那么解决方案可能会非常简单。

\n
import Foundation\n\nvar text = """\n    Let's split some text into sentences.\n    The text might include dates like Jan.13, 2020, words like S.A.E and numbers like 2.2 or $9,999.99 as well as emojis like \xe2\x80\x8d\xe2\x80\x8d\xe2\x80\x8d! How do I split this?\n"""\nvar sentences: [String] = []\ntext.enumerateSubstrings(in: text.startIndex..., options: [.localized, .bySentences]) { (tag, _, _, _) in\n    sentences.append(tag ?? "")\n}\n
Run Code Online (Sandbox Code Playgroud)\n

当然,有很多方法可以用纯 Swift 来做到这一点。这是快速而肮脏的分割:

\n
let simpleText = """\nThis is a very simple text.\nIt doesn't include dates, abbreviations, and numbers, but it includes emojis like \xe2\x80\x8d\xe2\x80\x8d\xe2\x80\x8d! How do I split this?\n"""\n\nlet sentencesPureSwift =  simpleText.split(omittingEmptySubsequences:true) {  $0.isPunctuation && !Set("',").contains($0)}\n
Run Code Online (Sandbox Code Playgroud)\n

它可以通过 进行精炼reduce()

\n