Вот менее впечатляющее, но более объяснительное решение:
Давайте начнем с определения примерного словаря и предложения в вашем вопросе:
sentence = 'I am done; Look at that, cat!'
dictionary = {
'!': 'sentinel',
',': 'sentinel',
',': 'sentinel',
'I': 'pronoun',
'that': 'pronoun',
'cat': 'noun',
'am': 'verb',
'Look': 'verb',
'done': 'verb',
'at': 'preposition',
';': 'preposition',
}
Для моего решения я определяю рекурсивный анализфункция, метко названная parse
.parse
сначала разбивает предложение на слова по пробелам, а затем пытается классифицировать каждое слово, просматривая его в предоставленном словаре.Если слово не может быть найдено в словаре (поскольку к нему прилагается некоторая пунктуация и т. Д.), parse
затем разбивает слово на составляющие токены и рекурсивно анализирует его оттуда.
def parse(sentence, dictionary):
# split the words apart by whitespace
# some tokens may still be stuck together. (i.e. "that,")
words = sentence.split()
# this is a list of strings containing the 'category' of each word
output = []
for word in words:
if word in dictionary:
# base case, the word is in the dictionary
output.append(dictionary[word])
else:
# recursive case, the word still has tokens attached
# get all the tokens in the word
tokens = [key for key in dictionary.keys() if key in word]
# sort all the tokens by length - this makes sure big words are more likely to be preserved. (scat -> s, cat or sc, at) check
tokens.sort(key=len)
# this is where we'll store the output
sub_output = None
# iterate through the tokens to find if there's a valid way to split the word
for token in tokens:
try:
# pad the tokens inside each word
sub_output = parse(
word.replace(token, f" {token} "),
dictionary
)
# if the word is parsable, no need to try other combinations
break
except:
pass # the word couldn't be split
# make sure that the word was split - if it wasn't it's not a valid word and the sentence can't be parsed
assert sub_output is not None
output.append(sub_output)
# put it all together into a neat little string
return ' '.join(output)
Вот как вы могли бы это использовать:
# usage of parse
output = parse(sentence, dictionary)
# display the example output
print(output)
Я надеюсь, что мой ответ дал вам более глубокое понимание другого метода, который можно использовать для решения этой проблемы.
Тада!?