I think the question is self-explanatory but here goes the detailed meaning of the question.
I want to extract all trigrams from text files using the nltk
library having adjectives as the middle term.
Example Text – A red ball was with the good boy.
Example of output –
JavaScript
x
2
1
('A','red','ball'), ('the','good','boy')
2
and so on
Advertisement
Answer
This code should do it:
JavaScript
1
16
16
1
import nltk
2
from nltk.tokenize import word_tokenize
3
4
nltk.download('punkt')
5
nltk.download('averaged_perceptron_tagger')
6
7
text = word_tokenize("He is a very handsome man. Her childern are funny. She has a lovely voice")
8
text_tags = nltk.pos_tag(text)
9
results = list()
10
for i, (txt, tag) in enumerate(text_tags):
11
if tag in ["JJ", "JJR", "JJS"]:
12
if (i > 0) and (i < len(text_tags)-1):
13
results.append((text_tags[i-1][0], txt, text_tags[i+1][0]))
14
15
# output: [('very', 'handsome', 'man'), ('are', 'funny', '.'), ('a', 'lovely', 'voice')]
16