2016-11-23 42 views
0

我正在嘗試搜索數組中的句子中的關鍵字。數組的數據來自用戶的輸入,因此無法知道他們將輸入什麼內容。我該如何做到這一點,並記住哪些關鍵詞被保存了哪個句子?關鍵詞可以是任何單詞,例如(to,the,apache,koala,supercalifragilisticexpialidocious)。我希望計算機能夠分開每個句子並儘可能單獨檢查它們。在數組中搜索關鍵字中的每個句子 - Swift

func separateAllSentences() { 
    userInput.enumerateSubstrings(in: userInput.startIndex ..< userInput.endIndex, options: .bySentences) { userInput, _, _, _ in 
     if let sentence = userInput?.trimmingCharacters(in: .whitespacesAndNewlines), let lastCharacter = sentence.characters.last { 
      switch lastCharacter { 
      case ".": 
       self.statementsArray.append(sentence) 
      case "?": 
       self.questionsArray.append(sentence) 
      default: 
       self.unknownArray.append(sentence) 
      } 
     } 
    } 

    print("questions: \(questionsArray)") 
    print("statements: \(statementsArray)") 
    print("unknown: \(unknownArray)") 
} 

回答

0

這種快速(版本0)解決方案將匹配「但」到「蝴蝶」(我會解決了你),但它仍然說明了基本原則。遍歷關鍵字和句子,並將找到的匹配記錄爲指示關鍵字和句子的一對數字。

let keywords = ["and", "but", "etc"] 
let sentences = ["The owl and the butterfly.", "Fine words butter no parsnips.", "And yet more sentences, etc."] 

var matches = [(Int, Int)]() 
for keyIndex in 0..<keywords.count { 
    for sentenceIndex in 0..<sentences.count { 
     if sentences[sentenceIndex].lowercased().contains(keywords[keyIndex].lowercased()) { 
      matches.append((keyIndex, sentenceIndex)) 
     } 
    } 
} 
print(matches) 
0

也許爲每個句子創建一個對象?使用與該句子匹配的句子String和一個字符串數組的屬性。因此,當您將每個句子追加到其相應的數組時,您就會創建一個對象。

class Sentence { 
    var sentence: String? 
    var stringArray: [String] = [] 
} 

使用此方法https://stackoverflow.com/a/25523578/3410964檢查句子String是否包含您之後的字符串。

func checkForString(stringToFind: String, sentenceObjects: [Sentence]) -> [Sentence] { 
    for sentenceObject in sentenceObjects { 
    if (sentenceObject.sentence.contains(stringToFind) { 
     sentenceObject.stringArray.append(stringToFind) 
    } 
    } 
    return sentenceObjects 
} 

然後這將返回一個句子對象數組,每個句子對象都有一個匹配的字符串數組。

希望我已經理解你的問題了!

1

簡單:

let keywords = ["and", "but", "etc"] 
let sentences = ["The owl and the butterfly.", "Fine words butter no parsnips.", "And yet more sentences, etc."] 

sentences.map({ sentence in 
    (sentence: sentence, tags: keywords.filter({ sentence.containsString($0) })) 
}) 

結果:

[("The owl and the butterfly.", ["and", "but"]), 
("Fine words butter no parsnips.", ["but"]), 
("And yet more sentences, etc.", ["etc"])] 
+1

沒必要用'flatMap(_ :)',因爲你申請不返回一個可選或序列變換。只需使用map(_ :)'。 – Hamish

+0

@哈米什,好點! – zepar