I am a Junior Python developer and got stuck recently trying to solve a task. Please, share any ideas you have to optimize the code.
The main task:
transform a sentence according to a pattern: "det" "noun" is \ that is "adj" ==> "det" "adj" "noun". For example, "the sky that is beautiful" ==> "the beautiful sky"; "a car that is old" ==> "an old car".
I've come to the solution (and am willing to find out a more optimized one):
def shorten(phrase):
tokens = nltk.word_tokenize(phrase)
tags = nltk.pos_tag(tokens)
needed_tags = ['DT', 'NN', 'NNS', 'JJ', 'JJR', 'JJS', 'VBG']
for i in range(len(tags)):
word = [word for word, pos in tags if (pos in needed_tags)]
word[0], word[1], word[2], word[3], word[4], word[5] = word[0], word[2], word[3], word[4], word[5], word[1]
for i in word[1]:
if i == 'a' and 'o' and 'i' and 'u' and 'e' and 'y':
word[0] = 'an'
return ' '.join(word)
return ' '.join(word)
It basically does the whole job: using this code, I can transform the sentence "the tasks that are easy and interesting smart yet difficult" into the needed simplified form "the easy interesting smart difficult tasks".
However, if there are more adjectives than needed, the structure is corrupted (since I switch the words manually, instead of a program to identify that the word is an adjective and then move it before a noun).
If any clarification is needed, please, let me know.