搜索数组中的每个句子以获取关键字 - Swift

时间:2016-11-23 21:53:08

标签: arrays swift function

我正在尝试在数组中的句子中搜索关键字。数组的数据来自用户的输入,因此无法知道它们将键入的内容。我怎么能这样做并记住为哪个句子保存了哪些关键字?关键词可以是任何单词,如(to,the,apache,koala,supercalifragilisticexpialidocious)。我希望计算机将每个句子分开并在可能的情况下单独检查它们。

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

3 个答案:

答案 0 :(得分: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 :(得分:0)

这个快速(版本0)解决方案将匹配&#34;但是&#34;蝴蝶&#34;蝴蝶&#34; (我会向你解决这个问题),但它仍然说明了基本原则。迭代关键词和句子,并将匹配记录为一对数字,表示关键词和句子。

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)

答案 2 :(得分:0)

也许为每个句子创建一个对象?具有句子String的属性和已与句子匹配的字符串数组。因此,当您将每个句子附加到其相应的数组时,您将创建一个对象。

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

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

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

然后返回一个句子对象数组,每个句子对象都有一个已匹配的字符串数组。

希望我理解你的问题!