2017-03-25 25 views
1

我試圖改變由說出的單詞設置的文本字段中單詞的顏色(例如:開心,傷心,生氣等)。 如果該單詞被多次說出,則它不起作用。例如,如果我說:「我感到高興,因爲我的貓對我很好,我的兄弟讓我難過,我很高興。」它只會改變第一個'快樂'的顏色,我不完全確定爲什麼。Swift 3.0 Speech to Text:改變單詞的顏色

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 

} 

謝謝!

回答

0

您的代碼有兩個問題。

第一個問題是你的例子中的標點符號。當你這樣做:

text.components(separatedBy:" ") 

結果數組的樣子:

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

悲哀中有一個週期,將不匹配什麼在你的情感詞典鑰匙是否只是「傷心」 。

第二個問題是:

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

既然你有「快樂」兩次在你的例子,這將只返回的幸福中第一次出現的範圍,所以纔有了第一個快樂將被高亮顯示。

最好的方法是對情感字典中的每個鍵使用正則表達式。然後你可以打電話給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 { $0.range } 
      for range in allMatches { 
       string.addAttribute(NSForegroundColorAttributeName, value: emotionDictionary[key], range: range) 
      } 
     } 
     catch { } 
    } 

    return string 
} 
+0

非常感謝你爲這個偉大的** **的答案! – Mariella