2017-08-24 59 views
1

我需要從句子中獲取人名。我想提取名稱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) 
} 

回答

3

當您有其他的文本時,您可以用「」分隔它。然後第一和secont元素是第一個和最後一個名字

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

//first name 
print(array[0]) 

//last name 
print(array[1]) 
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

+0

總是會有'和'關鍵字。 –

+0

@ImBatman檢查更新的答案 –

+1

@ImBatman你真的應該像Abizern的回答一樣使用詞法標記符。 – Fogmeister

2

可以按如下步驟實現:

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 

這樣的話,應該dropFirst(11)如果你是工作正常相當肯定說:「我的名字是」應該是名之前,由於其性格的數量是11

0

您可以刪除前綴字符串「我的名字是大衛「,然後用」「分隔。

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

這對斯威夫特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. 
} 
在我的判決,不能出示擔保
+1

該死!你在我之前就到了那裏。我即將發佈類似的答案。值得注意的是,這是可能的iOS 5和以上,但稍微難以使用:D – Fogmeister

+2

你知道有多少次發生在我身上?太陽照耀着每個人有時:) – Abizern