从句子中提取名称

时间:2017-08-24 08:44:23

标签: ios swift

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

示例:My Name is David Bonds and i live in new york.我要提取名称David Bonds

My Name is肯定会出现在每一句话中。但在名称之后它可以包含句子的其余部分或者可能没有任何内容。从这answer开始,我能够达到My Name is的目的。但它将打印出所有句子的其余部分。我想确保它只会抓取next two words

 if let range = conversation.range(of: "My Name is") {
    let name = conversation.substring(from: range.upperBound).trimmingCharacters(in: .whitespacesAndNewlines)
    print(name)
 }

6 个答案:

答案 0 :(得分:7)

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.
}

答案 1 :(得分:3)

如果您有其他文本,可以用“”分隔。然后,第一个和secont元素是名字和姓氏

let array = text.components(separatedBy: " ")

//first name
print(array[0])

//last name
print(array[1])

答案 2 :(得分:2)

您可以按如下方式实施:

!empty($corpex_opt ['corpex_header_layout'] ) == '3'

作为评论,let myString = "My Name is David Bonds and i live in new york." // all words after "My Name is" let words = String(myString.characters.dropFirst(11)).components(separatedBy: " ") let name = words[0] + " " + words[1] print(name) // David Bonds 应该可以正常工作,如果你非常确定那么"我的名字是"应该在名称之前,因为它的字符数是11。

答案 3 :(得分:1)

使用以下代码

let sen = "My Name is David Bonds and i live in new york."

let arrSen = sen.components(separatedBy: "My Name is ")
print(arrSen)

let sen0 = arrSen[1]

let arrsen0 = sen0.components(separatedBy: " ")
print("\(arrsen0[0]) \(arrsen0[1])")

<强>输出:

enter image description here

答案 4 :(得分:0)

您可以删除前缀字符串&#34;我的名字是David&#34;然后用&#34; &#34;

Output

答案 5 :(得分:0)

取决于您希望数据的方式:

let string = "My Name is David Bonds and i live in new york."

let names = string.components(separatedBy: " ")[3...4]
let name  = names.joined(separator: " ")