gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:07:26 26 4
gpt4 key购买 nike

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

 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

最佳答案

先写一个内建类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

关于swift - 从字符串中删除停用词而不修剪 Swift 中的其他词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49123066/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com