5

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?

appu
  • 51
  • 3
  • could you give a example of your default implementation? is it only the number or does your response also contain other stuff like "foo five bar" -> "foo 5 bar"? – zero3nna Jul 18 '18 at 13:15
  • Default implementation is simple UISearchBar. I didnt write any code for voice to text conversion. When the user clicks on mic button in the keyboard, voice to text conversion starts. Yes response contains other stuff too. – appu Jul 19 '18 at 04:04

2 Answers2

2

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
CodeBender
  • 35,668
  • 12
  • 125
  • 132
  • Thanks for the answer, but my response contains the non numbers too. My doubt is that is there anything we can change any value in speech recognizer, such that if the voice contains number, the converted text format would be in integer format. For ex if voice is 'Top five places', I need converted text as 'Top 5 places' – appu Jul 19 '18 at 04:09
  • Ok. Perhaps a string extension that searches for spelled out names and then performs a replacement? The trick would be handling combined numbers (37, 412, etc.). – CodeBender Jul 19 '18 at 14:39
0

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

zero3nna
  • 2,770
  • 30
  • 28