0

This is a part of a larger program. Here is what I am trying to do.

  1. Pass a sentence to the scan method.
  2. Have the sentence contain numbers.
  3. Split the sentence into it's different terms.
  4. append to a list a tuple, the first expression in the tuple being the type of thing that the word or sentence element fits into, the second being the word or number.

Here is what I am trying:

def scan(self, sentence):
    self.term = []

    for word in sentence.split():
        if word in direction:
            self.term.append(('direction', word))
        elif word in verbs:
            self.term.append(('verb', word))
        elif word in stop:
            self.term.append(('stop', word))
        elif word in nouns:
            self.term.append(('noun', word))
        elif type(int(word)) == 'int':
            self.term.append(('number', int(word)))
        else:
            self.term.append(('error', word))

    return self.term



print lexicon.scan('12 1234')

This is a method in a class, the print statement is outside. The part I am concerned with and having trouble with is this:

elif type(int(word)) == int:
    self.term.append(('number', int(word)))

It should work for any natural number [1, infinity)

Edit: I run into a problem when I try to scan('ASDFASDFASDF')

Where's-the-pi
  • 186
  • 2
  • 14
  • 1
    what are you doing exactly? type(int(word)) == int ??? you convert it to int then check if it's int? – zero.zero.seven May 20 '13 at 17:52
  • 1
    Duplicate of http://stackoverflow.com/questions/5424716/python-how-to-check-if-input-is-a-number-given-that-input-always-returns-stri of http://stackoverflow.com/questions/16488278/how-to-check-if-a-variable-is-an-integer-or-a-string of http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-in-python of ... – Alexei Sholik May 20 '13 at 17:58

3 Answers3

5

Since you only need positive integers, then try elif word.isdigit(): (note that this will also accept "0").

PaulMcG
  • 56,194
  • 14
  • 81
  • 122
1
if word.lstrip('0').isdigit(): 
    #append

Using the .lstrip('0') will remove leading 0's and cause strings such as '0' and '000' to not pass the check. Simply doing if word.isdigit() and word !='0' will not exclude '00' or any other string that is just multiple '0's

You could also use a try/except/else to see if it is an int and respond accordingly

try:
    int(s)
except ValueError:
    print s, 'is not an int'
else:
    print s, 'is an int'
Ryan Haining
  • 30,835
  • 10
  • 95
  • 145
0

You could apply int to word and catch a ValueError if it's not a number.

George
  • 566
  • 1
  • 4
  • 14