내가 파이썬 어려운 방법 알아보기 행사 (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...
}
작동하는 방법, 어,이에 숫자와 정의되지 않은 단어 "개방적"정의가 있습니까?
업데이트.
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"블록을 추가하십시오. 이렇게하면 코드 중복을 줄일 수 있으며 더 중요한 것은 사용자의 의도를 독자에게 알릴 수 있습니다.다음은 try/except/else를 설명하는 이유와 그 이유를 설명하는 좋은 질문입니다. http://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else -in-python –