swift 从句子中提取出一个名字

cgfeq70w  于 2023-09-30  发布在  Swift
关注(0)|答案(6)|浏览(118)

我需要从一个句子中得到人名。
例如: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)
 }
9ceoxa92

9ceoxa921#

快到Swift 4,iOS 11的时候了,在这里使用NSLinguisticTagger会更容易一些。
因此,为了将来的参考,您可以使用NSLinguisticTagger从句子中提取名称。这不依赖于命名标记后面的名称或两个单词的名称。
这是来自一个Xcode 9Playground

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

2023年9月编辑

自从我写了这个答案已经有一段时间了,事情已经发生了变化。NSLinguisticTagger在iOS 14中被弃用,支持新的NaturalLanguage框架
现代版本的做法是:

import UIKit
import NaturalLanguage

let text = "My Name is David Bonds and I live in new york."

// Create an NSTagger instance based on NameTypes
let tagger = NLTagger(tagSchemes: [.nameType])
tagger.string = text

// Configure the tagger
let options: NLTagger.Options = [.joinNames]
let tags: [NLTag] = [.personalName]

tagger.enumerateTags(in: text.startIndex..<text.endIndex, unit: .word, scheme: .nameType, options: options) { tag, tokenRange in
    // Get the most likely tag, and print it if it's a named entity.
    if let tag = tag,
       tags.contains(tag) {
        print("\(text[tokenRange])")
    }
   return true
}
zpjtge22

zpjtge222#

当你有文本的其余部分时,你可以用“”来分隔它。然后first和second元素是first和last name

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

//first name
print(array[0])

//last name
print(array[1])
ckocjqey

ckocjqey3#

您可以按如下方式实现它:

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

需要说明的是,如果您 * 非常确定 *“My Name is“应该在名称之前,那么dropFirst(11)应该可以正常工作,因为它的字符数是11。

uqzxnwby

uqzxnwby4#

使用下面的代码

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])")

输出:

zbdgwd5y

zbdgwd5y5#

您可以删除前缀字符串“My Name is大卫“,然后用““分隔。

var sentence = "My Name is David Bonds and"
let prefix = "My Name is "

sentence.removeSubrange(sentence.range(of: prefix)!)
let array = sentence.components(separatedBy: " ")
print("Name: ", array[0],array[1])  // Name:  David Bonds
kgsdhlau

kgsdhlau6#

根据您需要数据的方式:

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: " ")

相关问题