iOS speech to text conversion in number format

大兔子大兔子 提交于 2019-12-31 02:01:08

问题


Currently I'm using default iOS speech to text conversion without adding any code for it. When the user says 'five', it is displayed as 'five' or '5'. But, I need it to be converted as '5' always. Is there anything I can do with SFSpeechRecognizer or any other way to achieve this?


回答1:


This can get you started, but it is not able to handle mixed strings that contain a number AND a non-number. Ideally, you would need to process each word as it comes through, but then that has potential effects for combined numbers (thirty four) for example.

let fiveString = "five"
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .spellOut

print(numberFormatter.number(from: fiveString)?.stringValue) // 5

let combinedString = "five dogs"
print(numberFormatter.number(from: combinedString)?.stringValue) // nil

let cString = "five hundred"
print(numberFormatter.number(from: cString)?.stringValue) // 500

let dString = "five hundred and thirty-seven"
print(numberFormatter.number(from: dString)?.stringValue) // 537



回答2:


You could try to build a simple string extention like so:

extension String {

    var byWords: [String] {
        var byWords:[String] = []
        enumerateSubstrings(in: startIndex..<endIndex, options: .byWords) {
            guard let word = $0 else { return }
            byWords.append(word)
        }
        return byWords
    }

    func wordsToNumbers() -> String {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .spellOut

        let formattedString = self.byWords.map {
            return numberFormatter.number(from: $0)?.stringValue ?? $0
        }

        return formattedString.joined(separator: " ")
    }
}

This is a untested (not run / performance not checked) example



来源:https://stackoverflow.com/questions/51402470/ios-speech-to-text-conversion-in-number-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!