2016-11-23 48 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

相关问题