這對斯威夫特4,iOS的11在使用NSLinguisticTagger
是更容易一點的時間差不多。
因此,爲了將來的參考,您可以使用NSLinguisticTagger從句子中提取名稱。這不取決於命名標記後面的名稱,也不取決於兩個詞的名稱。
這是從Xcode的9遊樂場
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.
}
在我的判決,不能出示擔保
總是會有'和'關鍵字。 –
@ImBatman檢查更新的答案 –
@ImBatman你真的應該像Abizern的回答一樣使用詞法標記符。 – Fogmeister