[python] check command

be:proud
3 min readFeb 19, 2017

--

telegram(참고)을 통해서 command를 처리해야 하는데 다양한 command를 체크하기 위해서 효율적인 방법을 찾고 있습니다. 아직 좋은 방법을 찾지 못해서(계속 검색 중) 무식한 방법이지만 필요에 의해서 급하게 만들었습니다. command가 많지 않아서 그나마 다행이네요^^; command가 많았다면 이런 방법은 좋지 못할듯하네요.

ALLOWED_COMMAND = {
"There": {
"is": {
"a": {
"monster": True,
"dragon": True
}
},
"are": {
"monsters": True,
"dragons": True,
}
},
"My": {
"name": {
"is": {
"monster": True,
"dragon": True
}
}
}
}

ALLOWED_COMMAND에 설정된 key값으로 허용 여부를 판별합니다.

def is_allowed_command(allowed_command, command, index):
for k, v in allowed_command.items():
if k == command[index]:
print('{} == {}'.format(k, command[index]))
if isinstance(v, dict):
index += 1
if len(command) <= index:
return None

return is_allowed_command(v, command, index)
elif isinstance(v, BooleanType):
return v
else:
print('{} != {}'.format(k, command[index]))
continue

”There is a monster” 실행 결과

text = "There is a monster".split(' ')
result = check_allowed_command(ALLOWED_COMMAND, text, 0)
-- 실행 결과There == There
is == is
a == a
monster == monster
result: True

“There is a tree” 실행 결과

text = "There is a tree".split(' ')
result = check_allowed_command(ALLOWED_COMMAND, text, 0)
-- 실행 결과There == There
is == is
a == a
monster != tree
dragon != tree
result: None

”My name is monster” 실행 결과

text = "My name is monster".split(' ')
result = check_allowed_command(ALLOWED_COMMAND, text, 0)
-- 실행 결과
There != My
My == My
name == name
is == is
monster == monster
result: True

“My firstname is monster” 실행 결과

text = "My firstname is monster".split(' ')
result = check_allowed_command(ALLOWED_COMMAND, text, 0)
-- 실행 결과
There != My
My == My
name != firstname
result: None

좀 무식하죠? ㅎㅎ 더 엘레강스한 코딩을 하기 위해 열심히 검색(?)을 해야겠습니다.

--

--