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?

Community
  • 1
  • 1
C. Kelly
  • 162
  • 9
  • It is duplicate: http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python – ADR Apr 03 '17 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. – user2357112 Apr 03 '17 at 21:42
  • 1
    Example for comment above `for tokenizer in [MWETokenizer, ReppTokenizer, SExprTokenizer]: tokenizer (testTxt)` – ADR Apr 03 '17 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. – C. Kelly Apr 03 '17 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. – C. Kelly Apr 04 '17 at 14:21

0 Answers0