ios - 从句子中提取名字

标签 ios swift

我需要从句子中获取人名。

示例:我叫 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/

相关文章:

ios - 有没有办法找出 View Controller 是否从导航堆栈中弹出?

ios - CoreData 中的数据验证问题

ios - 单击 iPhone 的 UItabButton 时如何通过 swift 重新加载网站页面

json - 为什么编码键或 keyDecodingStrategy 不起作用?

ios - Swift - 通过 segue 传递值

ios - 在后台获取位置更新 - 仅适用于国家/地区更改 iOS

ios - 呈现 UIViewController 并将数据传回呈现 View

ios - Branch 打不开 App Store 链接

swift - Int 和 Double 在 Swift 中共享一个公共(public)父类

ios - 无法在动态表格 View 单元格中限制按钮大小