删除字符串中的停用词而不修剪Swift中的其他单词

问题描述 投票:0回答:4

我使用以下代码从字符串中删除停止单词,但它最终修剪其他单词,我只想删除字符串中的特定单词而不修剪其他单词。

 import Foundation

var sentence = "God have created the creatures at his best"
let wordToRemove = "at"


if let range = sentence.range(of: wordToRemove) {
   sentence.removeSubrange(range)
}

print(sentence) // God have creed the creures  his best
swift string
4个回答
1
投票

首先编写Build-In类String的扩展

extension String {

    func contains(word : String) -> Range<String.Index>?
    {
        return self.range(of: "\\b\(word)\\b", options: .regularExpression)
    }
}

然后编写以下代码以从句子中删除特定单词

var sentence = "God have created the creatures at his best"
let wordToRemove = "at"

if let range  = sentence.contains(word: wordToRemove) {
     sentence.removeSubrange(range)
     print(sentence)
}

 //Output : God have created the creatures  his best

1
投票

通过我对停用词的理解,它们可以出现在句子中的任何一点,包括作为第一个或最后一个词。因此,解决方案应支持在句子中的任何位置删除它们。

import Foundation

var sentence = "at God have created the creatures at his best at"
let wordsToRemove = ["at", "his"]

let words = sentence.components(separatedBy: " ")
sentence = words.filter({ wordsToRemove.contains($0) == false }).joined(separator:" ")

// sentence is now "God have created the creatures best"

0
投票
import Foundation

var sentence = "God have created the creatures at at at at his best"
let words = [" at ", " his "]
var index = 0
while index < words.count {
    let word = words[index]
    if let range = sentence.range(of: word) {
        sentence = sentence.replacingOccurrences(of: word, with: " ", options: [], range: range)
    } else {
        index += 1
    }
}

print(sentence)

上帝创造了最好的生物


0
投票
func replaceText(){
        var sentence = "At God have created the creatures at his best aatckkat at."
        var arr = [String]()
        sentence.enumerateSubstrings(in: sentence.startIndex..<sentence.endIndex, options: .byWords) { (str, r1, r2, stop) in
            //Condition for words to be removed
            if str! != "at" && str! != "At"{
                arr.append(str!)
            }
        }
        sentence = ""
        for word in arr{
            sentence += "\(word) "
        }
        print("new altered sentence -> \(sentence)")
    }

你可以尝试这种方式。

© www.soinside.com 2019 - 2024. All rights reserved.