0

I have a list of related function names which I want to iterate thru, calling the function held in the variable. But no matter how I try it, I get: "TypeError: 'TweetTokenizer' object is not callable"

Following the solution in Calling a function of a module from a string with the function's name in Python (of which it is suggested this question is a duplicate), finds the functions in the nltk module and assigns them. But my resulting "tok_alg" function is still failing as not callable. Any advice on why this is happening would be appreciated.

#!/usr/bin/env python

import nltk
import os
testTxt="I'll have a Bloomin' Onion."
Tokenizers = [ 'Tweet', 'MWE', 'TreebankWord' ]

for tokenizer in Tokenizers:
    tokz = tokenizer + 'Tokenizer'

    tok_alg = getattr(nltk, tokz)()
    result = tok_alg(testTxt)

    print(result)

Listing the functions does work, viz

for tokenizer in [ TweetTokenizer(), MWETokenizer() ]:
    result = tokenizer.tokenize(testTxt)

But the suggested conversion of str variables via getattr() is not working for NLTK. While this is elegant and practical, I need the string variables for other purposes. Surely there is some way to vivify these into a function call. What am I missing?

5
  • It is duplicate: stackoverflow.com/questions/3061/… Commented Apr 3, 2017 at 21:42
  • 2
    "I have a list of related function names which I want to iterate thru, calling the function held in the variable" - names are not functions. Don't make a list of names; make a list of actual functions. Commented Apr 3, 2017 at 21:42
  • 1
    Example for comment above for tokenizer in [MWETokenizer, ReppTokenizer, SExprTokenizer]: tokenizer (testTxt) Commented Apr 3, 2017 at 21:44
  • Many thanks, user2357112 and ADR. This was much more helpful than offhandedly closing the question. Very grateful, though it would've been great to have the question kept open for my further education in Python. Commented Apr 3, 2017 at 23:39
  • #moses-koledoye, please unmark as duplicate. There are issues at play which go beyond the simple solution offered in the other question, whether in the NLTK library or other subtleties of python when converting strings to functions. Commented Apr 4, 2017 at 14:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.