Python, ImportError: cannot import name AbstractLazySequence - python

I am using nltk but the problem I am facing does not seem to be related to nltk specifically.
I have a module named util.tokenize inside which there are some classes and I have the following first line:
util/tokenizer.py
from nltk.tokenize.regexp import RegexpTokenizer
...
class SentTokenizer(object):
def __init__(self, stem=False, pattern='[^\w\-\']+'):
self.alg = RegexpTokenizer(pattern, gaps=True)
def __call__(self, text):
return self.alg.tokenize(text)
....
if __name__ == '__main__':
s_t = SentTokenizer()
s_t('blah blah')
When I call those classes from another module, say test.py everything seems to work, but running the tokenize.py module directly causes ImportError.
File "tokenize.py", line 1, in <module>
...
File "Python27\lib\site-packages\nltk\corpus\reader\util.py", line 28, in <module>
from nltk.util import AbstractLazySequence, LazySubsequence, LazyConcatenation, py25
ImportError: cannot import name AbstractLazySequence
What could be the problem? Why it works when called from other modules?
test.py
from util.tokenize import SentTokenizer
s_t = SentTokenizer()
print s_t('blah blah')
Platform is Windows.

We determined that this was being caused by a namespace conflict with nltk.tokenize and the user's tokenize.py. After renaming tokenize.py, everything worked properly.

Related

ModuleNotFoundError when using a function from a custom module that imports another custom module

I have a folder structure similar to this (my example has all the necessary bits):
web-scraper/
scraper.py
modules/
__init__.py
config.py
website_one_scraper.py
Where config.py just stores some global variables. It looks a bit like:
global var1
var1 = "This is a test!"
Within website_one_scraper.py it looks like this:
import config
def test_function():
# Do some web stuff...
return = len(config.var1)
if __name__ == "__main__":
print(test_function)
And scraper.py looks like this:
from module import website_one_scraper
print(website_one_scraper.test_function())
website_scraper_one.py works fine when run by itself, and thus the code under if __name__ == "__main__" is run. However, when I run scraper.py, I get the error:
ModuleNotFoundError: No module named 'config'
And this is the full error and traceback (albeit with different names, as I've changed some names for the example above):
Traceback (most recent call last):
File "c:\Users\User\Documents\Programming\Work\intrack-web-scraper\satellite_scraper.py", line 3, in
<module>
from modules import planet4589
File "c:\Users\User\Documents\Programming\Work\intrack-web-scraper\modules\planet4589.py", line 5, in
<module>
import config
ModuleNotFoundError: No module named 'config'
Also note that In scraper.py I've tried replacing from modules import website_one_scraper with import website_one_scraper, from .modules import website_one_scraper, and from . import website_one_scraper, but they all don't work.
What could the cause of my error be? Could it be something to do with how I'm importing everything?
(I'm using Python 3.9.1)
In your website_scraper_one.py, instead of import config.py try to use from . import config
Explanation:
. is the current package or the current folder
config is the module to import

Python wont allow me to import .py files from same directory

So I'm just starting to learn Python, and I am learning classes and imports, but for some reason even when I follow the same code as my book say to do, I get a traceback error.
Traceback (most recent call last):
File "C:/Users/Programming/Desktop/Programs/EX40/main.py", line 1, in <module>
import objects.py
ModuleNotFoundError: No module named 'objects.py'; 'objects' is not a package
Here is both my Python files in which I'm trying to link:
main.py
import objects.py
print(MyStuff.tangerine)
objects.py
class MyStuff(object):
def __init__(self, arm):
self.tangerine = 'And now a thousand years between'
self.arm = arm
def apple(self):
print('I AM CLASSY APPLES!')
Try using
import objects
Because it takes py as a module in the objects file which does not exist
import objects.py is not a valid import
https://docs.python.org/3/reference/import.html
Try
from objects import MyStuff
Instantiating the class:
mystuff = MyStuff("arm value")
print(mystuff.tangerine)

Python cannot import from another file name not defined

I am trying to import a custom function from another python file but keep getting an error NameError: name 'testme' is not defined. I confirmed that I am importing the file correctly according to this SO post and that the function is top level. What else can I try to fix this?
My main python file is:
import sys
import dbconn
#from dbconn import testme #<----did not work
dev=True
if(dev):
categId='528'
pollIds=[529,530,531]
else:
categId=str(sys.argv[1])
pollIds=[529,530,531]
df=testme(categIds)#callServer(categId,pollIds)
df
if(not categId.isdigit):
print('categ id fail. expected digit got: '+categId)
.....
and dbconn.py:
import pymysql #pip3 install PyMySQL
import pandas as pd
from scipy.stats.stats import pearsonr
from scipy import stats
def testme(categIds):
try:
df=categIds
except Exception as e:
print("broke")
return categIds
Not sure if it makes a difference but I am running the main python file from within a Jupyter notebook, and have a compiled version of dbconn.py in the same directory
In response to the suggestions I tried:
df=dbconn.testme(categIds)
got the error:
module 'dbconn' has no attribute 'testme'
You Have to follow these fox exact import
1)import <package>
2)import <module>
3)from <package> import <module or subpackage or object>
4)from <module> import <object>
in your case, you have tried
from dbconn import testme
you have to use only packages in from section and module in import section
like >>
from testme import dbconn

Python 3 - importing .py file in same directory - ModuleNotFoundError: No module named '__main__.char'; '__main__' is not a package

I'm using Python 3.6 on Windows 10. I have 2 .py files in the same directory, char.py, and char_user.py, as follows:
char.py:
# char.py
import cv2
#######################################################################################################################
class Char:
# constructor #####################################################################################################
def __init__(self):
self.contour = None
self.centerOfMassX = None
self.centerOfMassY = None
# end def
# end class
char_user.py:
# char_user.py
import os
import cv2
# I've tried this various ways, see more comments below
from .char import Char
#######################################################################################################################
def main():
char = Char()
char.centerOfMassX = 0
char.centerOfMassY = 0
print("finished main() without error")
# end main
#######################################################################################################################
if __name__ == "__main__":
main()
No matter what I try, on the line in char_user.py where I'm attempting to import file char.py, class Char, I get the error:
ModuleNotFoundError: No module named '__main__.char'; '__main__' is not a package
Here are some of the ways I've tried the import statement in char_user.py:
from .char import Char
from . import Char
import Char
import char
I've tried both with and without an empty __init__.py in the same directory.
I've consulted these posts but none have been able to provide a resolution:
How to import the class within the same directory or sub directory?
ModuleNotFoundError: What does it mean __main__ is not a package?
ModuleNotFoundError: No module named '__main__.xxxx'; '__main__' is not a package
This is the 1st time in Python 3 I've attempted to import a script that I wrote in the same directory (done this many times in Python 2 without concern).
Is there a way to do this? What am I missing?
I was able to get this working with from char import Char, because you are trying to import the class Char from script char.
As far as I am aware, the line from .char import Char is only used if both files were part of a python module (with its own __init__.py), which they are not. In that case, .char explicitly references the file char.py inside the same module folder, rather than from importing from some other module installed to PYTHONPATH.
try this:
from char import Char

package import and NameError

I have some troubles with importation of self-made modules, I just can't see what I am doing wrong.
I have a package named basics, which has all my base classes
I have a second package named components, and every module in componentsuses the modules from basics.
I have a script file, located in another folder, which calls upon the basics and components modules.
I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "H:/scripts/CIF_utilities/scripts/hello world.py", line 11, in <module>
TW=TextWriter(r'H:/scripts/CIF_utilities/components')
File "H:\scripts\CIF_utilities\components\textwriter.py", line 23, in __init__
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
NameError: global name 'Layout' is not defined
There is my script: hello world.py
#hello world.py
import basics
from components.textwriter import *
TW=TextWriter(r'H:/scripts/CIF_utilities/components')
cell=TW.writeText('Hello World',30e3)
cell.draw()
layout=Layout()
layout.addCell(cell)
layout.workCell=cell
layout.exportCIF('hello world',os.getcwd())
textwriter.py is the one giving the error. In init, I load some data from a preformatted file using the Layout class (which will make the import)
in textwriter.py
#texwriter.py
import basics
import os, os.path, sys
import re
from numpy import *
from scipy import *
class TextWriter:
def __init__(self,pathToCIF=None):
if pathToCIF==None:
path=os.path.split(textwriter.__file__)[0]
else:
path=pathToCIF
###line that crashes is here
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
self.alphabet=layout.workCell
There is the layout.py class:
#layout.py
import basics
from numpy import *
from scipy import *
import Tkinter
import tkFileDialog
import os, os.path
import re
import datetime
class Layout:
countCell=0
#classmethod
def getNewNumber(self):
Layout.countCell+=1
return Layout.countCell
def __init__(self,File=None):
self.cellList=[]
self.layerList=[]
self.nameFile=""
self.comments=""
self.workCell=None
if File!=None:
self.importCIF(File)
the init.py of the basics package contains all the necessary importations:
#__init__.py in basics folder
from baseElt import *
from cell import *
from layout import *
from transformation import *
the init.py from components is empty
I am currently using the anaconda 64bits distribution (python 2.7 if I recall well)
Thanks for your much needed help!
Since Layout is imported in basics/__init__.py, it only exists in the basics namespace, not in helloworld.py. Either access it with
layout = basics.Layout()
or explicitly import Layout into helloworld.py with
from basics import Layout
In textwriter.py, you want to switch
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
for
layout=basics.Layout(File=os.path.join(path,'alphabet.CIF'))
You may have similar problems along your code. it is good to note that it is not pythonic to use
from package import *
It is recommended to instead use
from package_or_module import specific_item
import package_or_module
Remember, if you import with regular import you have to use the module/package name to access the object you want (i.e. basics.Layout).

Categories