如何在Swift中计算给定文本中的句子数?

如何在Swift中计算给定文本中的句子数?,swift,string,count,sentence,Swift,String,Count,Sentence,我想创建一个操场,计算给定文本的句子数 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) le

我想创建一个操场,计算给定文本的句子数

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()
这应该起作用:

   let input = "That would be the text . it hast 3. periods. "
   let occurrencies = input.characters.filter { $0 == "." || $0 == "?" }.count
   print(occurrencies)
   //result 3

只需在
charset
中添加字符,即可区分句子:

我假设
目前:

    let input = "That would be the text. it hast 3? periods."
    let charset = CharacterSet(charactersIn: ".?,")
    let arr = input.components(separatedBy: charset)
    let count = arr.count - 1
此处
arr
为:

["That would be the text", " it hast 3", " periods", ""]
将计数减少1,以获得实际的句子


<强>注释:< /强>如果您不想考虑<代码>,“< /代码>,则将其从<代码>字符集> />代码>

到目前为止,我可以看到您需要使用它们进行拆分。并按如下方式修剪空白:

func sentencecount () {

    let result = input.trimmingCharacters(in: .whitespaces).split(separator: ".")

   print ("The Average Sentence length is \(result.count)") // 3
}

祝你好运

您可以使用
枚举子字符串(在:范围内)
并使用选项

let input = "Hello World !!! That would be the text. It hast 3 periods."
var sentences: [String] = []
input.enumerateSubstrings(in: input.startIndex..., options: .bySentences) { (string, range, enclosingRamge, stop) in
    sentences.append(string!)
}
另一种方法是使用子字符串数组而不是字符串:

var sentences: [Substring] = []
input.enumerateSubstrings(in: input.startIndex..., options: .bySentences) { (string, range, enclosingRamge, stop) in
    sentences.append(input[range])
}


亲爱的Matt我会编辑我的帖子谢谢我会检查;)它说:游乐场执行失败:错误:textcoach.playerd:76:30:错误:不明确地使用'filter'让发生率=input.characters.filter{$0='“|$$0==”?“}.count您有哪个版本的swift?非常感谢您,Ankit。这里我得到的最终解决方案要感谢您:func sentencecount()->Double{let input=“这就是文本。它有3个句点。”let charset=CharacterSet(charactersIn:“.?,”),let arr=input.components(separatedBy:charset)let arrcount=Double(arr.count)let doubleone:Double=1 let count:Double=arrcount-doubleone打印(“平均句子长度为”,countofwords/count,“Words”)return(count)}@Valentin,welcome:)我一直在等待这个:)–请注意,您可以在:input.startIndex…
中将范围指定为“单边范围”
,进行比较
print(sentences)   // "["Hello World !!! ", "That would be the text. ", "It hast 3 periods."]\n"
print(sentences.count)  // "3\n"