3

this must be simple but I'm missing it somehow. I have the code:

import nltk

f=open('...\\t.txt','rU')
raw=f.read()
tokens = nltk.word_tokenize(raw)
print nltk.pos_tag(tokens)

which returns for instance:

"[('processes', 'NNS'), ('a', 'DT'), ('sequence', 'NN'), ('of', 'IN'), ('words', 'NNS')]

I was wondering how I could just collected solely all 'NN' for example or all 'DT' AND 'IN' instead of every member of the string.

thanks in advance

1 Answer 1

5

You can extract only the tags you want with a list comprehension, e.g.:

>>> tags = nltk.pos_tag(tokens)
>>> dt_tags = [t for t in tags if t[1] == "DT"]
>>> dt_tags
[('a', 'DT')]
2
  • perfect, and just duplicate if I want to find DTs and NNS tags2 = [t for t in nltk.pos_tag(tokens) if t[1] == "NNS"] tags2
    – saph_top
    Commented Feb 19, 2014 at 14:01
  • Yes, you could even make a dictionary with tags for each type: all_tags = {tag: [t for t in tags if t[1] == tag] for tag in ["DT", "NNS", ...]}
    – jonrsharpe
    Commented Feb 19, 2014 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.