Swift 3.0 语音转文本:改变单词的颜色

Swift 3.0 Speech to Text: Changing Color of Words

我正在尝试更改由口语设置的文本字段中单词的颜色(例如:快乐、悲伤、愤怒等)。 如果这个词被说了不止一次,它就不起作用。例如,如果我说 "I'm feeling happy because my cat is being nice to me. My brother is making me sad. I'm happy again." 它只会改变第一个 'happy' 的颜色,我不确定为什么。

func setTextColor(text: String) -> NSMutableAttributedString {

    let string:NSMutableAttributedString = NSMutableAttributedString(string: text)
    let words:[String] = text.components(separatedBy:" ")

        for word in words {
            if emotionDictionary.keys.contains(word) {
                let range:NSRange = (string.string as NSString).range(of: word)
                string.addAttribute(NSForegroundColorAttributeName, value: emotionDictionary[word], range: range)
            }
        }
    return string

}

谢谢!

你的代码有两个问题。

第一个问题是你的例子中的标点符号。当你这样做时:

text.components(separatedBy:" ")

生成的数组如下所示:

["I'm", "feeling", "happy", ..., "making", "me", "sad."]

如果关键字只是 "sad"。

,那么悲伤中有一个句点,并且不会与您的情感字典中的内容匹配

第二个问题是:

let range:NSRange = (string.string as NSString).range(of: word)

由于您的示例中有两次 "happy",这只会 return 第一次出现 happy 的范围,因此只会突出显示第一个 happy。

最好的方法是为情感字典中的每个键使用正则表达式。然后,您可以调用 regex.matches,这将为您提供 所有 次快乐或悲伤的范围。然后您可以遍历它并适当地设置颜色。

这会执行以下操作并且应该适用于您的示例:

func setTextColor(text: String) -> NSMutableAttributedString {

    let string:NSMutableAttributedString = NSMutableAttributedString(string: text)

    for key in emotionDictionary.keys {
        do {
            let regex = try NSRegularExpression(pattern: key)
            let allMatches = regex.matches(in: text, options: [], range: NSMakeRange(0, string.length))
                                  .map { [=13=].range }
            for range in allMatches {
                string.addAttribute(NSForegroundColorAttributeName, value: emotionDictionary[key], range: range)
            }
        }
        catch { }
    }

    return string
}