如何在Swift中统计指定文本的句子数量?附Playground代码问题
I want to create a Playground that counts the number of sentences in a specified text. Here's my current code, but it's not working correctly:
let input = "That would be the text . it hast 3. periods. " func sentencecount() { let periods = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters) let periods = input.components(separatedBy: spaces) let periods2 = Int (words.count) print ("The Average Sentence length is \(periods2)") } sentencecount()
Can someone show me the right way to implement sentence count in Swift?
First, let's break down the issues in your current code:
- You’ve declared two variables named
periodsin the same scope, which will throw a compile error. - The
spacesvariable isn’t defined anywhere, so that line will fail to compile. - You’re trying to use
words.countbutwordsisn’t declared either. - Your logic doesn’t actually target sentence-ending punctuation (like
.,!,?) to count sentences.
Here are two reliable approaches to count sentences in Swift:
1. Simple Approach (Basic Punctuation Split)
If your text doesn’t have edge cases like abbreviations (e.g., "Mr. Smith"), you can split on common sentence-ending punctuation, then clean up empty strings:
let input = "That would be the text. It has 3 periods. Hello world!" func countSentences(_ text: String) -> Int { // Define sentence-ending punctuation let sentenceEnders = CharacterSet(charactersIn: ".!?") // Split the text using these characters let components = text.components(separatedBy: sentenceEnders) // Filter out empty strings caused by trailing punctuation or extra spaces let nonEmptyComponents = components.filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } return nonEmptyComponents.count } print(countSentences(input)) // Output: 3
2. Accurate Approach (Using Natural Language Framework)
For texts with abbreviations or complex sentence structures, Apple's Natural Language framework is far more accurate—it understands context to avoid counting abbreviations as sentence endings.
First, import the framework, then use NLTagger to identify sentence boundaries:
import NaturalLanguage let input = "Mr. Smith went to the store. He bought 3 apples! Did you see him?" func countSentencesWithNL(_ text: String) -> Int { let tagger = NLTagger(tagSchemes: [.sentence]) tagger.string = text var sentenceCount = 0 let range = NSRange(text.startIndex..., in: text) tagger.enumerateTags(in: range, unit: .sentence, scheme: .sentence, options: [.omitWhitespace, .omitPunctuation]) { _, _, _ in sentenceCount += 1 return true } return sentenceCount } print(countSentencesWithNL(input)) // Output: 3 (correctly ignores "Mr." as a sentence end)
Key notes for the Natural Language approach:
- It handles edge cases like abbreviations, hyphenated words, and non-English languages much better.
- It’s available on iOS 12+, macOS 10.14+, watchOS 5+, and tvOS 12+.
内容的提问来源于stack exchange,提问作者Valentin

