【问题标题】:How to find a keyword in a decomposed string on swift?如何在swift的分解字符串中找到关键字?
【发布时间】:2020-04-22 19:09:11
【问题描述】:

在尝试制作聊天机器人时,我设法分解了句子,​​但我不知道如何检查是否有关键字(在我的数组中) 我的代码:

var array1 = ["dog", "cat", "bird"]     //my arrays "key words"
var array2 = ["wolf", "sheep", "pig"]
var array3 = ["horse", "frog", "bear"]
var sentence = "" // This would be whatever we write in the text field

let random = Int.random(in: 0...2) 

if random == 0 {
    sentence = "I like my dog"
}
else if random == 1 {
    sentence = "I like my pig"
}
else if random == 2 {
    sentence = "I like my horse"
}

let result = sentence.split(separator: " ") //this make the decomposition of the sentence
print(result)

然后我尝试检查是否有关键字但它不起作用,这是我尝试的:

for counter in 0...array1.count-1 {   
    if result == array1[counter] {
        print("cool!")
    }
}

它告诉我:二元运算符“==”不能应用于“[String.SubSequence]”(又名“Array”)和“String”类型的操作数

【问题讨论】:

  • for word in array1 { if result.contains(word[...]) { print("cool!") } }

标签: arrays swift chatbot keyword swift5


【解决方案1】:

就个人而言,我只会将您句子中的每个单词转换为String

let words = sentence.split(separator: " ").map { String($0) }

并使用集合而不是数组:

var keywords1: Set = ["dog", "cat", "bird"]     //my arrays "key words"
var keywords2: Set = ["wolf", "sheep", "pig"]
var keywords3: Set = ["horse", "frog", "bear"]

...

if !keywords1.isDisjoint(with: words) {
   print("Cool!")
}

因为有了集合,检查交叉点要容易得多。

【讨论】:

  • Sets 当然是一个更有效的解决方案,因为它是 O(1) 与 contains 的 O(n),但在运行时将子字符串数组转换为字符串数组并再次因为每一个新句子都是非常低效的。将关键字 Sets 声明为 Sets of Substrings,您可以完全跳过映射步骤,编译器可以在编译时执行此转换(因此不涉及任何开销)。
【解决方案2】:

result 是一个数组,array1[counter] 是一个字符串;您不能将数组与字符串进行比较,您可以将字符串/子字符串与字符串/子字符串或数组与数组进行比较。您可以比较result == array1result[x] == array[y]xy 是数组的索引。如果你想测试一个字符串是否在一个数组中,那么你可以在一个数组上调用.contains(...),参见documentation。然而,由于您的结果数组是一个子字符串数组,您需要确保您的测试数组也是如此:

let array1 = ["dog", "cat", "bird"] as [Substring]
// ...
for word in array1 {
    if result.contains(word) { print("Cool") }
}

【讨论】:

    猜你喜欢
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多