我需要从句子中获取人名。
示例:我叫 David Bonds,我住在纽约。
我想提取姓名 David Bonds
。
My Name is
肯定会出现在每个句子中。但在名字之后它可以包含句子的其余部分或者可能什么都没有。来自这个answer我能够到达 My Name is
的地步。但它会打印出所有句子的其余部分。我想确保它只会抓取接下来的两个词
。
if let range = conversation.range(of: "My Name is") {
let name = conversation.substring(from: range.upperBound).trimmingCharacters(in: .whitespacesAndNewlines)
print(name)
}
最佳答案
Swift 4, iOS 11 的时间差不多了,在其中使用 NSLinguisticTagger
会更容易一些。
因此,为了将来引用,您可以使用 NSLinguisticTagger 从句子中提取名称。这不取决于命名标记后的名称,或两个单词的名称。
这是来自 Xcode 9 Playground
import UIKit
let sentence = "My Name is David Bonds and I live in new york."
// Create the tagger's options and language scheme
let options: NSLinguisticTagger.Options = [.omitWhitespace, .omitPunctuation, .joinNames]
let schemes = NSLinguisticTagger.availableTagSchemes(forLanguage: "en")
// Create a tagger
let tagger = NSLinguisticTagger(tagSchemes: schemes, options: Int(options.rawValue))
tagger.string = sentence
let range = NSRange(location: 0, length: sentence.count)
// Enumerate the found tags. In this case print a name if it is found.
tagger.enumerateTags(in: range, unit: .word, scheme: .nameType, options: options) { (tag, tokenRange, _) in
guard let tag = tag, tag == .personalName else { return }
let name = (sentence as NSString).substring(with: tokenRange)
print(name) // -> Prints "David Bonds" to the console.
}
关于ios - 从句子中提取名字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45856934/