Learn Python the hard way 习题48

本文通过一个简单的Python类实现,介绍了如何创建一个词典匹配类,并详细解释了如何扫描句子以识别方向、动词、停顿词、名词及数字等元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# coding:utf-8 

class lexicon(object):

	def __init__(self):
		# dictionary to find word on
		self.directions = ['south', 'north', 'east', 'west']
		self.verbs = ['go', 'kill', 'eat']
		self.stops = ['the', 'in', 'of']
		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 result
		
# 测试未实例化 否则会unbound
lexicon = lexicon()

练习48是第一次自己写代码,出现了很多问题。

1.unboud:习题的测试代码没有实例化lexicon,需要在模块中实例化。

2.关于怎么在列表中查找是否存在:

自己写成这样:

if(self.direction.count(word) == 1):
后来看到别人的代码:

if word in self.directions:


就可以了,,,

3.循环的条件:

也是:

while(len(words) != 0):
 	word = words.pop(0)


这样就行(还不用定义word了:

for word in words:
不过学到了不少list的方法。



还有的疑问:

书上是:from ex48 import lexicon

而我:from Game.lexicon import lexicon。 不加'.lexicon'就会importError

查询import的用法,点是子文件夹













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值