簡體   English   中英

如何檢查數組中的句子在Swift中是否包含確切的單詞?

[英]How can I check if sentences in array contains exact words in Swift?

例如,我有以下數組:

var reviews = ["Skating is good in Austria", 
"I loved the Spanish food, it had so many varieties and 
it was super super delicious. The price was a little bit high but 
it was worth it. People who don't like spicy food might need 
to think twice as it could be a little bit problematic for them.", 
"I didn’t like the Indian food!", 
"People were really friendly, I enjoyed being there."]

var words = ["Skating", "Food", "Climbing"]

現在,我想檢查一下這些評論是否包含我的一句話。

面臨的挑戰是:一個或多個評論可以包含這些單詞,我想找到這些評論,並將它們添加到數組中並打印。

為此,我這樣做:

var arr = [String]()

for review in reviews {
    for word in words {
        if review.containsString(word) {
            arr.append(review)
        }
    }
    print(arr)
}

但這僅顯示第一句話:

["Skating is good in Austria"]

因此,我想檢查一個或多個評論是否包含數組中的這些單詞,然后將所有這些匹配的評論放入arr數組中。

有人可以幫我嗎? 我很困惑為什么只需要進行一次審核並在之后停止

您需要將print語句移出循環。

像這樣:

var arr = [String]()

for review in reviews {
    for word in words {
        if review.containsString(word) {
            arr.append(review)
        }
    }
}
print(arr)

另外,如果您不想得到重復的評論,我將使用set而不是數組: var arr = Set<String>()

另外,可能是需要區分大小寫的字符串比較的情況。 在您的單詞數組中按food更改Food ,然后重試。

要使完整的不區分大小寫的循環正常工作,請嘗試以下操作:

for review in reviews {
    for word in words {
        if review.lowercaseString.containsString(word.lowercaseString) {
            arr.append(review)
        }
    }
}
print(arr)

如果您想忽略字符串的大小寫,只需使用array filter方法以這種方式嘗試,它將減少循環代碼。

var predicateString = [String]()
for word in words {
    predicateString(String(format:"SELF CONTAINS[cd] %@", word)
}
let predicate = NSPredicate(format: "%@",predicateString.joined(separator: " || "));
let filteredArray = reviews.filter { predicate.evaluateWithObject($0) };
print(filteredArray)

您可以使用函數式編程

首先,讓我們創建一個小寫關鍵字數組(我假設您要區分大小寫)。

let keywords = words.map { $0.lowercaseString }

下一個

let matchingSentences = reviews.filter { sentence  in
    let lowerCaseSentence = sentence.lowercaseString
    return keywords.contains { keyword in sentence.rangeOfString(keyword) != nil }
}

結果

matchingSentences.forEach { print($0) }

Skating is good in Austria
I loved the Spanish food, it had so many varieties and it was super super delicious. The price was a little bit high but it was worth it. People who don't like spicy food might need to think twice as it could be a little bit problematic for them.
I didn’t like the Indian food!

短版

let res = reviews.filter { sentence in keywords.contains { sentence.lowercaseString.rangeOfString($0) != nil } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM