This is my solution to the exercise 48 of Learn Python the hard way by Zed Shaw. Please visit the link for testing suite and requirements.
I'm worried about my the word banks I have created (COMPASS, VERBS, etc...) as this seems a duplication from the testing code.
I'm also afraid my handling might have gone overboard as all I needed it for was finding out which string items could be converted to integers.
1 COMPASS= ['north','south','east','west']$
2 VERBS = ['go', 'kill', 'eat']$
3 STOPS = ['the', 'in', 'of']$
4 NOUNS = ['bear', 'princess']$
5 $
6 import string$
7 def scan(sentence):$
8 action = []$
9 #TODO: it seems there might be a way to combine these if statments$
10 for word in sentence.split(' '):$
11 lword = string.lower(word)$
12 try:$
13 if lword in COMPASS:$
14 action.append(('direction', word))$
15 elif lword in VERBS:$
16 action.append(('verb', word))-$
17 elif lword in STOPS:$
18 action.append(('stop', word))$
19 elif lword in NOUNS:$
20 action.append(('noun', word))$
21 elif int(lword):$
22 action.append(('number', int(word)))$
23 except:$
24 action.append(('error', word))$
25 return action$
26 $
1 Answer 1
lword = string.lower(word)
There is no need to import the string module for this, you can use:
lword = word.lower()
As for this:
elif int(lword):
Probably better as
elif lword.isdigit():
As for your exception handling
except:
action.append(('error', word))
You should almost never use a bare except. You should catch a specific exception, and put a minimal amount of code in the try block. In this case you could have done something like
try:
actions.append( ('number', int(word) )
except ValueError:
actions.append( ('error', word) )
Explore related questions
See similar questions with these tags.