简体   繁体   中英

Select only 'NN' and 'VB' words from NTLK pos_tag

I need to print only 'NN' and 'VB' words from an entered sentence.

import nltk
import re
import time

var = raw_input("Please enter something: ")


exampleArray = [var]


def processLanguage():
    try:
        for item in exampleArray:
            tokenized = nltk.word_tokenize(item)
            tagged = nltk.pos_tag(tokenized)
            print tagged

            time.sleep(555)


    except Exception, e:
        print str(e)

processLanguage()

How about changing

    print tagged

to

    print [(word, tag) for word, tag in tagged if tag in ('NN', 'VB')]

You might need to use the first 2 characters of the POS tag, see NLTK - Get and Simplify List of Tags

nn_vb_tagged = [(word,tag) for word, tag in tagged 
                if tag.startswith('NN') or tag.startswith('VB')]

You can try this:

example = "This is a sample sentence, showing off the stop words filtration.!"
word_tokens = word_tokenize(example)
pos = nltk.pos_tag(word_tokens)
selective_pos = ['NN','VB']
selective_pos_words = []
for word,tag in pos:
     if tag in selective_pos:
         selective_pos_words.append((word,tag))
print(selective_pos_words)

By adding your selective parts of speech in the list "selective_pos", you can select any of your preferable word.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM