I am writing a python program on Windows using Python 2.7. Basically, it's a program that takes a 5-digit, negative & positive, number from user & spells it out in English using num2word & then speaks it out too. I have used espeak & pyttsx both but i'm getting errors in all of them. I have tried this:

num = raw_input('Please enter your 5 digit number:')
while len(num) != 5 or (not num.isdigit()):
    print 'Not a 5 digit number'
    num = raw_input('Please enter your 5 digit number:')
num = int(num)

def spellnum(num,join=True):
    #Lists of number words

        thousands = ['','thousand','million']
        tens = ['','ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
        teens = ['','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
        units = ['','one','two','three','four','five','six','seven','eight','nine'] 
        #Empty List for number words
        words = [] 
        #zero case
        if num==0: words.append('zero')
        #how to handle negative numbers
        if num < 0: words.append('negative') 
        num = abs(num)
        #a series of steps to process the numbers and turn them into words
        numStr = '%d'%num
        numStrLen = len(numStr)
        groups = (numStrLen+2)/3
        numStr = numStr.zfill(groups*3)
        for i in range(0,groups*3,3):
            h,t,u = int(numStr[i]),int(numStr[i+1]),int(numStr[i+2])
            g = groups-(i/3+1)
            if h>=1:
                words.append(units[h])
                words.append('hundred')
            if t>1:
                words.append(tens[t])
                if u>=1: words.append(units[u])
            elif t==1:
                if u>=1: words.append(teens[u])
                else: words.append(tens[t])
            else:
                if u>=1: words.append(units[u])
            if (g>=1) and ((h+t+u)>0): words.append(thousands[g]+',')
        #final joining of parts
            if join: return ' '.join(words)
        return words

print 'Your number is: ', spellnum(num)

import pyttsx
engine = pyttsx.init()
engine.setProperty('rate', 70)

voices = engine.getProperty('voices')
for voice in voices:
    print "Using voice:", repr(voice)
    engine.setProperty('voice', voice.id)
    engine.say(num)
engine.runAndWait()

Output was:

Please enter your 5 digit number:34342
Your number is:  thirty four thousand,

Traceback (most recent call last):
  File "C:\Python27\prj.py", line 48, in <module>
    engine = pyttsx.init()
  File "C:\Python27\lib\site-packages\pyttsx\__init__.py", line 39, in init
    eng = Engine(driverName, debug)
  File "C:\Python27\lib\site-packages\pyttsx\engine.py", line 45, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
  File "C:\Python27\lib\site-packages\pyttsx\driver.py", line 64, in __init__
    self._module = __import__(name, globals(), locals(), [driverName])
  File "C:\Python27\lib\site-packages\pyttsx\drivers\sapi5.py", line 19, in <module>
    import win32com.client
ImportError: No module named win32com.client

First, it's not spelling the complete number that the user provided. For e.g.: I entered 20300 & it said "twenty thousand,", that's it. It didn't say the proper "Twenty thousand, three hundred".
Second, when i entered -20300, it returned "not a 5-digit number". I know that this has something to do with .isdigit method that i used, i don't know what to do about it so that negative numbers can also be considered as proper inputs.
Third, i have tried to make it say the complete spelling of numbers by using Espeak & pyttsx both but it keeps returning errors. I tried this:

import subprocess
text = int(str(num))
subprocess.call('espeak '+text, shell=True)

Output was:

Please enter your 5 digit number:35345
Your number is:  thirty five thousand,

Traceback (most recent call last):
  File "C:\Python27\prj.py", line 49, in <module>
    subprocess.call('espeak '+text, shell=True)
TypeError: cannot concatenate 'str' and 'int' objects

Please know that i'm new to Python. Any kind of help is appreciated.

Dani AI

Generated

A short, practical checklist for (and anybody reading this later): three things to fix — stop the function from returning inside the loop, accept a signed 5‑digit value reliably, and pass text (not integers) to your TTS engine. Below are small, safe patterns you can apply.

Fix the “only the first group” problem by returning after the loop finishes (a return inside the loop exits the whole function on the first iteration). Move the join/return out of the loop so all groups are processed. (stackoverflow.com)

Validate input by converting to int and checking magnitude rather than using str.isdigit() (it rejects leading +/− signs). Example (Python 2.7 style):

def get_five_digit_number(prompt='Enter 5-digit number: '):
    while True:
        s = raw_input(prompt).strip()
        try:
            n = int(s)
        except ValueError:
            print "Enter a valid integer."
            continue
        if 10000 <= abs(n) <= 99999:
            return n
        print "Number must have exactly 5 digits (sign allowed)."

This handles negatives and avoids brittle string tests. (stackoverflow.com)

Use an existing converter + TTS instead of reinventing both. num2words gives clean English strings and pyttsx3 works offline on Windows (and mentions fixes for the missing win32 bits). Example:

from num2words import num2words
import pyttsx3

n = get_five_digit_number()
words = num2words(n, lang='en')
engine = pyttsx3.init()
engine.say(words)
engine.runAndWait()

Install with pip install num2words pyttsx3. (pypi.org)

If calling external programs (espeak) use argument lists instead of string concatenation — that avoids the str+int TypeError and quoting headaches:

import subprocess
subprocess.call(['espeak', words])

Also ensure packages are installed into the same Python interpreter you run (use python -m pip install ...). Test step-by-step: print the words string first, then pass it to the TTS. (docs.python.org)

I found and fixed a dew errors myself.

*few

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.