笨办法学python笔记(48)更复杂的用户输入

时间:2025-02-11 17:25:57

    习题48是要写出让测试代码正常运行的脚本。

功能上的要去:检查输入的字符串是否在创建的语汇表中。如果输入中含有数字字符串,要在处理结果中标记为‘number',如果不是数字也不再创建的语汇表中,则在结果中标记为'error'。

    习题测试代码如下

from  import *
from ex48 import lexicon


def test_direction():
	assert_equal(("north"), [('direction', 'north')])
	result = ("north south east")
	assert_equal(result, [('direction', 'north'),
						  ('direction', 'south'),
						  ('direction', 'east')])
						  
def test_verbs():
	assert_equal(("go"), [('verb', 'go')])
	result = ("go kill eat")
	assert_equal(result, [('verb', 'go'),
	                      ('verb', 'kill'),
						  ('verb', 'eat')])
				

def test_stops():
	assert_equal(("the"), [('stop', 'the')])
	result = ("the in of")
	assert_equal(result, [('stop', 'the'),
						  ('stop', 'in'),
						  ('stop', 'of')])
	
	
def test_noun():
	assert_equal(("bear"), [('noun', 'bear')])
	result = ("bear princess")
	assert_equal(result, [('noun', 'bear'),
	                      ('noun', 'princess')])

def test_numbers():
	assert_equal(("1234"), [('number', 1234)])
	result = ("3 91234")
	assert_equal(result, [('number', 3),
	                      ('number', 91234)])

def test_errors():
	assert_equal(("ASDFAFASDF"),[('error', 'ASDFAFASDF')])
	result = ("bear IAS princess")
	assert_equal(result, [('noun', 'bear'),
	                      ('error', 'IAS'),
			      ('noun', 'princess')])

要测试的代码如下:

lexicon = {
	'north': ('direction', 'north'),
	'south': ('direction', 'south'),
	'east': ('direction', 'east'),
	'west': ('direction', 'west'),
	
	'go': ('verb', 'go'),
	'kill': ('verb', 'kill'),
	'eat': ('verb', 'eat'),
	
	'the': ('stop', 'the'),
	'in': ('stop', 'in'),
	'of': ('stop', 'of'),
	
	'bear': ('noun', 'bear'),
	'princess': ('noun', 'princess'),
	}
	
def isnum(Num):
	try:
		return int(Num)
	except:
		return None


def scan(sentence):
	words = ()
	result = []
	
	for word in words:
		if isnum(word):
			(('number', int(word)))
		elif word in ():
			(lexicon[word])
		else:
			(('error', word))
	return result