Learn Python the hard way exercise 48__python

Source: Internet
Author: User
# Coding:utf-8 

Class Lexicon (object):

	def __init__ (self):
		# Dictionary to finds word on
		self.directions = [' South ', ' North ', ' East ', ' West ']
		self.verbs = [' Go ', ' kill ', ' eat ']
		self.stops = [', ', ', ' ', ']
		self. nouns = [' bear ', ' Princess ']
	
	def scan (self, sentence): Result
		
		= []
		
		words = Sentence.split ()
		
	# #  while (Len (words)!= 0):
		#	word = Words.pop (0) for
		word in words:
		# #	if (Self.direction.count ( Word = = 1):
			If Word in self.directions:
				result.append (' direction ', word)
			elif word in Self.verbs:
				result.append ((' verb ', word))
			elif Word in Self.stops:
				result.append ((' Stop ', word)
			elif Word In Self.nouns:
				result.append ((' noun ', word))
			else:
				try:
					word = int (word)
					result.append (' Number ', word ')
				except ValueError:
					result.append (' error ', word) ' return
		
results # test not instantiated Otherwise it will unbound
lexicon = Lexicon ()

Exercise 48 is the first time you write your own code, there are a lot of problems.

1.unboud: The test code for the exercise does not instantiate the lexicon and needs to be instantiated in the module.

2. about how to find the existence in the list:

Write It yourself:

if (self.direction.count (word) = = 1):
Later you see someone else's code:

If Word in self.directions:


It's OK,,,

3. Conditions of Circulation:

Also:

while (Len (words)!= 0):
	Word = words.pop (0)


This is OK (you don't have to define word:

For word in words:
But learned a lot of list method.



There are some questions:

The book is: from ex48 import Lexicon

And I: From Game.lexicon import Lexicon. Not adding ' lexicon ' will Importerror

Query import usage, point is subfolder













Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.