Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting all Nouns from a text file using nltk

Tags:

python

nltk

Is there a more efficient way of doing this? My code reads a text file and extracts all Nouns.

import nltk

File = open(fileName) #open file
lines = File.read() #read all lines
sentences = nltk.sent_tokenize(lines) #tokenize sentences
nouns = [] #empty to array to hold all nouns

for sentence in sentences:
     for word,pos in nltk.pos_tag(nltk.word_tokenize(str(sentence))):
         if (pos == 'NN' or pos == 'NNP' or pos == 'NNS' or pos == 'NNPS'):
             nouns.append(word)

How do I reduce the time complexity of this code? Is there a way to avoid using the nested for loops?

Thanks in advance!

like image 838
Rakesh Adhikesavan Avatar asked Nov 07 '15 20:11

Rakesh Adhikesavan


People also ask

How do I find a noun in Python?

if (val = = 'NN' or val = = 'NNS' or val = = 'NNPS' or val = = 'NNP' ): print (text, " is a noun." ) else : print (text, " is not a noun." )

What is NLTK Ne_chunk?

NLTK has already a pre-trained named entity chunker which can be used using ne_chunk() method in the nltk.chunk module. This method chunks a single sentence into a Tree. Code #1 : Using ne-chunk() on tagged sentence of the treebank_chunk corpus.

What is NLTK RegexpParser?

class nltk. RegexpParser (grammar, root_label=u'S', loop=1, trace=0)[source] A grammar based chunk parser. chunk. RegexpParser uses a set of regular expression patterns to specify the behavior of the parser.


2 Answers

If you are open to options other than NLTK, check out TextBlob. It extracts all nouns and noun phrases easily:

>>> from textblob import TextBlob
>>> txt = """Natural language processing (NLP) is a field of computer science, artificial intelligence, and computational linguistics concerned with the inter
actions between computers and human (natural) languages."""
>>> blob = TextBlob(txt)
>>> print(blob.noun_phrases)
[u'natural language processing', 'nlp', u'computer science', u'artificial intelligence', u'computational linguistics']
like image 131
Aziz Alto Avatar answered Oct 17 '22 11:10

Aziz Alto


import nltk

lines = 'lines is some string of words'
# function to test if something is a noun
is_noun = lambda pos: pos[:2] == 'NN'
# do the nlp stuff
tokenized = nltk.word_tokenize(lines)
nouns = [word for (word, pos) in nltk.pos_tag(tokenized) if is_noun(pos)] 

print nouns
>>> ['lines', 'string', 'words']

Useful tip: it is often the case that list comprehensions are a faster method of building a list than adding elements to a list with the .insert() or append() method, within a 'for' loop.

like image 29
Boa Avatar answered Oct 17 '22 12:10

Boa