NLTK function from string variable isn't callable [duplicate] - python

This question already has answers here:
import module from string variable
(7 answers)
How can I import a module dynamically given its name as string?
(10 answers)
Closed 5 years ago.
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?

Related

random.choices can't be imported? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
this may be an easy one so sorry for the post but I can't seem to get random.choices() to import
my code:
import random
scans = 100
foobar = []
for i in range(scans):
string = 'https://'
string.join(random.choices(string.ascii_lowercase + string.digits, k = url_len))
string.join(random.choice(domains_list))
foobar.append(string)
del string
I am getting:
AttributeError: 'module' object has no attribute 'choices'
as an output in the mac-os terminal.
I have tried:
restarting editor
using from random import choices instead(alongside) of import random
again sorry if this seems like a spam post but I have been googling for a while and have not found a single answer.
Thanks to all! :D
If you do your import like this, importing the function from the module:
from random import choices
Then your code needs to just refer to that function, since you haven't imported the module itself, so Python won't be aware of the module's name in your code:
choices(string.ascii_uppercase + string.digits, k = 10)
But if you instead import the whole module:
import random
Then your code needs to refer to both the module and the function, because the only way Python knows about the function is via the imported module:
random.choices(string.ascii_uppercase + string.digits, k = 10)
If you get this error:
AttributeError: 'module' object has no attribute 'choices'
Then that could mean you might also be using an old Python version which simply doesn't have choices, as it was added in Python 3.6.
If that's not the case, then you possibly have a file named random.py that's accidentally getting imported instead. See this question for more details if that's the case.
But without knowing more details about your python version and local files, it's impossible to say exactly why you in particular are getting that particular error.
Another issue in your above code is this line - it's overwriting your import string statement, and setting string to an actual string instead (your string was 'foobar' but any string would've caused the issue):
string = 'foobar'
When you refer to the string module right after, since you've overwritten it with the string 'foobar', trying to use the module at all (like string.ascii_uppercase for example) will result in this kind of error:
AttributeError: 'str' object has no attribute 'ascii_uppercase'

How do I get all the classes in a module? [duplicate]

This question already has answers here:
Python: get only classes defined in imported module with dir()?
(3 answers)
In Python, how do I get the list of classes defined within a particular file?
(4 answers)
Closed 2 years ago.
How do I get all the classes in a module? For example if a module has classes A, B and C, how do I get the names of all these classes through code?
Try this:
import importlib, inspect
inspect.getmembers(
importlib.import_module("your_module"),
inspect.isclass
)
this will give you what you are looking for.

Import a class with a string [duplicate]

This question already has answers here:
import module from string variable
(7 answers)
Closed 3 years ago.
Given dot-notation of a python class, how would I import it if it's given as a string?
For example:
>>> from ingest.models import ItemInstance
>>> ItemInstance
<class 'ingest.models.ItemInstance'>
Given the string, 'ingest.models.ItemInstance', how would I import that?
Note: the above referenced duplicated is primarily about importing a module. Here I'm looking to specifically import a class. For example:
s = "ingest.models.ItemInstance"
cls = s.split('.')[-1] # works with the given path, but not always
module = '.'.join(s.split('.')[:-1])
getattr(importlib.import_module(module), cls)
The answer provided below addresses this accurately.
In Python 2.7 and Python 3.1 or later, you can use importlib:
import importlib
i = importlib.import_module("module_name")
If you want to access the class, you can use getattr:
import importlib
module = importlib.import_module("module_name")
class_ = getattr(module, class_name)
instance = class_()

dynamic execute a function by a string like 'module.function' [duplicate]

This question already has answers here:
Python function pointer
(8 answers)
Closed 9 years ago.
if I have a string like 'module.function', How can I execute function just by one step?
likesomefunction('os.error','args')
You can dynamically get the modules using sys.modules and then you can use getattr to get the attributes from the module, like this
import sys
func = "os.error"
module, function = func.split(".", 1)
getattr(sys.modules[module], function)()
sys.modules can give only the modules which are already loaded. So, if you want to load a module dynamically you can use __import__ function like this
For example,
module, function = "math.factorial".split(".", 1)
print getattr(__import__(module), function)(5)
Output
120
All you need to do is
from module import function
and you'll be able to call
function(x, y, z)
in your code.

Python __import__ is only giving me top level module [duplicate]

This question already has answers here:
How can I import a module dynamically given its name as string?
(10 answers)
Closed 9 years ago.
I'm doing
module = __import__("client.elements.gui.button", globals(), locals(), [], 0)
But it's only returning client.
What is my problem?
That's what __import__ does.
When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name.
You're not really supposed to use __import__; if you want to import a module dynamically, use importlib.import_module.
Accepted answer is correct, but if you read on in the docs you'll find that this can be gotten around with an admittedly unsettling "hack" by using __import__ like so:
module = __import__('client.elements.gui.button', fromlist=[''])
It doesn't really matter what you pass in for fromlist so long as it's a non-empty list. This signals to the default __import__ implementation that you want to do a from x.y.z import foo style import, and it will return the the module you're after.
As stated you should use importlib instead, but this is still a workaround if you need to support Python versions < 2.7.
It only obtains the top level, but you can also work around this like so:
module_name = 'some.module.import.class'
module = __import__(module_name)
for n in module_name.split('.')[1:]:
module = getattr(module, n)
# module is now equal to what would normally
# have been retrieved where you to properly import the file

Categories

Resources