pythonnlpporter-stemmer

Need assistance with PorterStemmer in Python


I am running this code:

from nltk.tokenize import word_tokenize
from nltk.stem.porter import PorterStemmer
word = 'gardening'
tokens = word_tokenize(word.lower())
stemmer = PorterStemmer() # write code here
stemmed = [stemmer.stem(token) for token in tokens] # write your code here
print(stemmed)

I'm getting the output ['garden'] but how can I get the output without the brackets and quotes i.e., garden

I'm getting the output ['garden'] but how can I get the output without the brackets and quotes i.e., garden


Solution

  • You can use normal list indexing to get the result. For example:

    from nltk.tokenize import word_tokenize
    from nltk.stem.porter import PorterStemmer
    
    word = 'gardening'
    tokens = word_tokenize(word.lower())
    stemmer = PorterStemmer() # write code here
    stemmed = [stemmer.stem(token) for token in tokens] # write your code here
    
    # Print the first item in the list
    print(stemmed[0])
    

    Output:

    garden
    

    Or, for longer lists, you could use a for loop to print out each value:

    from nltk.tokenize import word_tokenize
    from nltk.stem.porter import PorterStemmer
    
    word = 'gardening'
    tokens = word_tokenize(word.lower())
    stemmer = PorterStemmer() # write code here
    stemmed = [stemmer.stem(token) for token in tokens] # write your code here
    
    for s in stemmed:
        print(s)