iOS speech to text conversion in number format

一笑奈何 提交于 2019-12-01 21:10:11

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

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

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