我想创建一个可以计算给定文本句子数的游乐场。
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()
答案 0 :(得分:2)
您可以使用enumerateSubstrings(in: Range)
并使用选项.bySentences
:
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])
}
print(sentences) // "["Hello World !!! ", "That would be the text. ", "It hast 3 periods."]\n"
print(sentences.count) // "3\n"
答案 1 :(得分:0)
这应该有效:
let input = "That would be the text . it hast 3. periods. "
let occurrencies = input.characters.filter { $0 == "." || $0 == "?" }.count
print(occurrencies)
//result 3
答案 2 :(得分:0)
只需在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,得到实际句子。
注意:如果您不想考虑" , "
,请将其从charset
移除。
答案 3 :(得分:0)
据我所知,您需要使用它们进行拆分。并修剪空格如下:
func sentencecount () {
let result = input.trimmingCharacters(in: .whitespaces).split(separator: ".")
print ("The Average Sentence length is \(result.count)") // 3
}
祝你好运!