1

I made a python file with several functions in it and I would like to use it as a module. Let's say this file is called mymod.py. The following code is in it.

from nltk.stem.porter import PorterStemmer                      
porter = PorterStemmer()  

def tokenizer_porter(text):                                                                                    
    return [porter.stem(word) for word in text.split()]  

Then I tried to import it in iPython and use tokenizer_porter:

from mymod import * 
tokenizer_porter('this is test')

The following error was generated

TypeError: unbound method stem() must be called with PorterStemmer instance as first argument (got str instance instead)

I don't want to put porter inside the tokenizer_porter function since it feels redundant. What would be the right way to do this? Also, is it possible to avoid

from mymod import * 

in this case?

Many thanks!

1 Answer 1

1

To access global variables in python you need to specify it in fucntion with global keyword

def tokenizer_porter(text):     
    global porter                                                                           
    return [porter.stem(word) for word in text.split()]  
Sign up to request clarification or add additional context in comments.

2 Comments

It works for me. Thanks. Is it possible to avoid from mymod import * in this case? I tried from mymod import tokenizer_porter and it didn't work.
Have you tried it after adding global? Cause it should work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.