Ios Swift 3.0语音到文本:更改单词颜色
我正在尝试更改文本字段中由口语设置的单词的颜色(例如:快乐、悲伤、愤怒等)。 如果这个词被说了不止一次,它就不起作用了。例如,如果我说,“我很高兴,因为我的猫对我很好。我的兄弟让我伤心。我又高兴了。”这只会改变第一个“高兴”的颜色,我不知道为什么Ios Swift 3.0语音到文本:更改单词颜色,ios,swift,speech-to-text,Ios,Swift,Speech To Text,我正在尝试更改文本字段中由口语设置的单词的颜色(例如:快乐、悲伤、愤怒等)。 如果这个词被说了不止一次,它就不起作用了。例如,如果我说,“我很高兴,因为我的猫对我很好。我的兄弟让我伤心。我又高兴了。”这只会改变第一个“高兴”的颜色,我不知道为什么 func setTextColor(text: String) -> NSMutableAttributedString { let string:NSMutableAttributedString = NSMutableAttribu
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."]
悲伤中有一个句号,如果关键是“悲伤”,它将与你的情感词典中的内容不匹配
第二个问题是:
let range:NSRange = (string.string as NSString).range(of: word)
由于您在示例中有两次“happy”,因此这将只返回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 { $0.range }
for range in allMatches {
string.addAttribute(NSForegroundColorAttributeName, value: emotionDictionary[key], range: range)
}
}
catch { }
}
return string
}
您的代码有两个问题 第一个问题是示例中的标点符号。当您这样做时:
text.components(separatedBy:" ")
生成的数组如下所示:
["I'm", "feeling", "happy", ..., "making", "me", "sad."]
悲伤中有一个句号,如果关键是“悲伤”,它将与你的情感词典中的内容不匹配
第二个问题是:
let range:NSRange = (string.string as NSString).range(of: word)
由于您在示例中有两次“happy”,因此这将只返回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 { $0.range }
for range in allMatches {
string.addAttribute(NSForegroundColorAttributeName, value: emotionDictionary[key], range: range)
}
}
catch { }
}
return string
}
非常感谢您的回答!非常感谢您的回答!