我正在尝试用swift在一个句子中进行关键字搜索。
例如给定
keywords=["黑色"、"袋子"、"爱"、"填充"]
句子1=";在一个充满爱的房子里有一个黑色的袋子;
句子2=";我们在一家商店里。柜台上有一个黑色的袋子;
句子3=";今天的海洋是美丽而可爱的">
我想在每个句子中搜索所有关键字,并返回包含所有关键字和不包含关键字的句子。所以输出应该
句子1:4个关键字句子2:3个关键字句子3:无
这是我解决的尝试
var RawSentences = ["There is a black bag in a house filled with love", "We are in a shop. There is a black bag on the counter", " The ocean is beautiful and lovely today"]
var keywords = ["black", "bag", "love", "filled"]
for item in RawSentences {
var matchkeywords: [String] = []
for kword in keywords{
if item.range(of:kword) != nil {
print("Yes!!!! (kword) is in (generatedString)")
matchkeywords.append(kword)
}
}
print("There are (String(matchkeywords.count)) keyword in (item)")
}
在swift中实现这一点的最佳方式是什么?
如果只想匹配整个单词,则需要使用正则表达式并为关键字添加边界。你也可以让你的搜索大小写和变音符号不敏感:
let sentences = ["There is a black bag in a house filled with love",
"We are in a shop. There is a black bag on the counter",
"The ocean is beautiful and lovely today"]
let keywords = ["black", "bag", "love", "filled"]
var results: [String: [String]] = [:]
for sentence in sentences {
for keyword in keywords {
let escapedPattern = NSRegularExpression.escapedPattern(for: keyword)
let pattern = "\b(escapedPattern)\b"
if sentence.range(of: pattern, options: [.regularExpression, .caseInsensitive, .diacriticInsensitive]) != nil {
results[sentence, default: []].append(keyword)
}
}
}
print(results) // ["There is a black bag in a house filled with love": ["black", "bag", "love", "filled"], "We are in a shop. There is a black bag on the counter": ["black", "bag"]]
如果你想知道关键词在句子中的位置,你只需要附加找到的范围而不是关键词:
var results: [String:[Range<String.Index>]] = [:]
for sentence in sentences {
for keyword in keywords {
let escapedPattern = NSRegularExpression.escapedPattern(for: keyword)
let pattern = "\b(escapedPattern)\b"
if let range = sentence.range(of: pattern, options: [.regularExpression, .caseInsensitive, .diacriticInsensitive]) {
results[sentence, default: []].append(range)
}
}
}
print(results) // ["We are in a shop. There is a black bag on the counter": [Range(Swift.String.Index(_rawBits: 1900544)..<Swift.String.Index(_rawBits: 2228224)), Range(Swift.String.Index(_rawBits: 2293760)..<Swift.String.Index(_rawBits: 2490368))], "There is a black bag in a house filled with love": [Range(Swift.String.Index(_rawBits: 720896)..<Swift.String.Index(_rawBits: 1048576)), Range(Swift.String.Index(_rawBits: 1114112)..<Swift.String.Index(_rawBits: 1310720)), Range(Swift.String.Index(_rawBits: 2883584)..<Swift.String.Index(_rawBits: 3145728)), Range(Swift.String.Index(_rawBits: 2097152)..<Swift.String.Index(_rawBits: 2490368))]]