我正在學習Python的困難的方法運動48和寫入lexicon
字典和scan
模塊上運行以下測試:「開放式」字典鍵? (LPTHW鍛鍊48相關)
from nose.tools import *
from ex47 import lexicon
def test_directions():
assert_equal(lexicon.scan("north"), [('direction', 'north')])
result = lexicon.scan("north south east")
assert_equal(result, [('direction', 'north'),
('direction', 'south'),
('direction', 'east')])
def test_verbs():
assert_equal(lexicon.scan("go"), [('verb', 'go')])
result = lexicon.scan("go kill eat")
assert_equal(result, [('verb', 'go'),
('verb', 'kill'),
('verb', 'eat')])
def test_stops():
assert_equal(lexicon.scan("the"), [('stop', 'the')])
result = lexicon.scan("the in of")
assert_equal(result, [('stop', 'the'),
('stop', 'in'),
('stop', 'of')])
def test_nouns():
assert_equal(lexicon.scan("bear"), [('noun', 'bear')])
result = lexicon.scan("bear princess")
assert_equal(result, [('noun', 'bear'),
('noun', 'princess')])
def test_numbers():
assert_equal(lexicon.scan("1234"), [('number', 1234)])
result = lexicon.scan("3 91234")
assert_equal(result, [('number', 3),
('number', 91234)])
def test_errors():
assert_equal(lexicon.scan("ASDFADFASDF"), [('error', 'ASDFADFASDF')])
result = lexicon.scan("bear IAS princess")
assert_equal(result, [('noun', 'bear'),
('error', 'IAS'),
('noun', 'princess')])
我最該想通的除數字和錯誤測試外。如果用戶輸入是詞典中未定義的單詞,則需要使用error
值名稱進行標記,如果是數字 - number
值名稱。顯然,我可以預先將所有要測試的輸入添加到字典中,但這是作弊。
我的字典裏是這樣的:
lexicon = {
'north': 'direction',
'princess': 'noun',
# etc...
}
有沒有辦法工作,呃,數字和不確定的話這個「開放式」的定義?
UPDATE。這裏是一個有效的解決方案:
def scan(sentence):
words = sentence.split()
pairs = []
for word in words:
try:
number = int(word)
tupes = ('number', number)
pairs.append(tupes)
except ValueError:
try:
word_type = lexicon[word]
tupes = (word_type, word)
pairs.append(tupes)
except KeyError:
tupes = ('error', word)
pairs.append(tupes)
return pairs
您的解決方案看起來不錯。我可能會提出一種改進方法:在「try」塊中嘗試儘可能少的行,併爲未發生異常時應該發生的情況添加「else」塊。這可以減少代碼重複,更重要的是,可以告訴讀者你的意圖是什麼。這是一個很好的SO問題,解釋try/except/else以及爲什麼你可以使用它:http://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else -in-python –