I am implementing the code
import sys
sys.path.append('/home/stepfourward/naivebayes/Naive-Bayes/')
from NaiveBayes import *
import os
DClasses = ["python", "java", "hadoop", "django", "datascience", "php"]
base = "learn/"
p = Pool()
for i in DClasses:
p.learn(base + i, i)
NaiveBayes module contains Pool.py that has the function learn():
def learn(self, directory, dclass_name):
"""
directory is a path, where the files of the class with the name dclass_name can be found
"""
x = DocumentClass(self.__vocabulary)
dir = os.listdir(directory)
for file in dir:
d = Document(self.__vocabulary)
print(directory + "/" + file)
d.read_document(directory + "/" + file, learn=True)
x = x + d
self.__document_classes[dclass_name] = x
x.SetNumberOfDocs(len(dir))
but when I am applying the method p.learn(base + i, i) metioned in code above I am getting attribute error.
AttributeError: 'Pool' object has no attribute 'learn'
How to eradicate this error. Thanks.
Here are the correct steps to use the said NaiveBayes library, after you have cloned the repo as explained elsewhere in a folder Naive-Bayes:
What you do
import sys
sys.path.append('Naive-Bayes/') # your own path here
from NaiveBayes import * # NO error here
p = Pool()
produces an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Pool' is not defined
What you should do:
import sys
sys.path.append('Naive-Bayes/')
from NaiveBayes.Pool import Pool # correct import
p = Pool() # runs OK now
DClasses = ["python", "java", "hadoop", "django", "datascience", "php"]
base = "learn/"
for i in DClasses:
p.learn(base + i, i)
At this point (but not before), I am getting an expected error, simply because your directories (e.g. learn/python) are not present in my machine:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/home/herc/SO/Naive-Bayes/NaiveBayes/Pool.py", line 29, in learn
dir = os.listdir(directory)
FileNotFoundError: [Errno 2] No such file or directory: 'learn/python'
but the clear message is that the Pool object and the learn method in Pool.py can indeed be accessed.
Tested with Python 3.4.3 in Ubuntu...
Related
I wrote a small Python script which takes all .jpeg img-files from a given "./Input" folder, creates a thumbnail from these images and saves them in a "./Output" file. It works perfectly fine when executed in an IDEA (In my case PyCharm), but when I created the executable with pyinstaller and tried to execute it, the following error appeared:
Traceback (most recent call last):
File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
[84693] Failed to execute script 'image_resizer' due to unhandled exception: No module named 'PIL'
[84693] Traceback:
Traceback (most recent call last):
File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
Here is my code:
import shutil
from PIL import Image
import glob, os
import time
output_directory = "./Output"
def photo_picker():
pictures = []
try:
for filename in glob.iglob("./Input/*.jpg"):
pictures.append(filename)
except FileNotFoundError:
print("could not execute")
return pictures
def create_output_folder():
if os.path.exists(output_directory):
shutil.rmtree(output_directory)
try:
os.mkdir(path=output_directory, mode=777)
except FileExistsError:
print("Could not execute")
def crop_image(img, new_name):
size = (2000, 2000)
with Image.open(img) as im:
im.thumbnail(size)
print(im.info)
img_name = f"{new_name}"
im.save(output_directory + "/" + img_name, "JPEG")
def main():
photos = photo_picker()
create_output_folder()
time.sleep(2)
for f in photos:
img_name_splitted = f.split("/")
img_name = img_name_splitted[len(img_name_splitted) - 1]
print(img_name)
crop_image(f, img_name)
return 0
if __name__ == "__main__":
main()
I installed the module Pillow, uninstalled it ,tried to install PIL (which didn't work). But as I mentioned before, when executing it in an IDEA it works.
I have few common functions written in file a.py which is called from file b.py. And, also I have few common functions written in file b.py which is called from file a.py. but when I try to run these files I get error as unable to import name. Below is the code for reference.
I have just provided an example below, these files have common piece of code in real scenario which is specific to a functionality and that is the reason its being called from one another
a.py code below
from b import get_partner_id
def get_customer_id(tenant_id):
customer_id = tenant_id + "tenant_name"
return customer_id
def get_partner_details():
partnerid = get_partner_id()
data = {"partnerId": partnerid}
print(data)
b.py code below
from a import get_customer_id
def get_partner_id():
customer_id = get_customer_id("7687")
env = 'sandbox-all' + customer_id
return env
get_partner_id()
Below is the error for reference,
Traceback (most recent call last):
File "C:/testCases/b.py", line 1, in <module>
from a import get_customer_id
File "C:\testCases\a.py", line 2, in <module>
from b import get_partner_id
File "C:\testCases\b.py", line 1, in <module>
from a import get_customer_id
ImportError: cannot import name 'get_customer_id'
I have a project with below structure:
TestDir.init.py contains:
from . import TestSubDirFile
TestDir.TestSubDirFile.py contains:
class TestSubDirFile:
def test_funct(self):
print("Hello World")
ds_scheduler.py contains:
from TestDir import TestSubDirFile as tp
def test_job():
testobj = tp.test_funct()
print("Test job executed.")
if __name__ == "__main__":
test_job()
Getting Output as:
Traceback (most recent call last):
File "C:/Python_Projects/Test/com/xyz/ds/ds_schedular.py", line 9, in <module>
test_job()
File "C:/Python_Projects/Test/com/xyz/ds/ds_schedular.py", line 5, in test_job
testobj = tp.test_funct()
AttributeError: module 'TestDir.TestSubDirFile' has no attribute 'test_funct'
As per your directory structure
ds_scheduler.py
TestDir -- Directory Name
- TestSubDirFile.py - Python filename
Within TestSubDirFile.py file you have defined your class with name TestSubDirFile.
from TestDir import TestSubDirFile as tp
As per your above import statement you are only accessing till the py file.
To access test_func() method within class you need to follow below steps.
tsdf = tp.TestSubDirFile()
tsdf.test_funct()
Hope this helps
When I try to execute this code
import surprise.dataset
file = 'ml-100k/u.data'
col = 'user item rating timestamp'
reader = surprise.dataset.Reader(line_format = col, sep = '\t')
data = surprise.dataset.Dataset.load_from_file(file, reader = reader)
data.split(n_folds = 5)
I get this error:
Traceback (most recent call last):
File "/home/user/PycharmProjects/prueba2/surprise.py", line 1, in <module>
import surprise.dataset
File "/home/user/PycharmProjects/prueba2/surprise.py", line 1, in <module>
import surprise.dataset
ModuleNotFoundError: No module named 'surprise.dataset'; 'surprise' is not a package
But surprise is installed. How can I use it?
If you want to import a submodule, instead of doing:
import surprise.dataset
do:
from surprise import dataset
then in the rest of the code, reference it as dataset instead of surprise.dataset (i.e. replace surprise.dataset.Reader with dataset.Reader). If you don’t want to update the rest of your code, you can also just import the whole surprise module instead with:
import surprise
I intend to perform a Newton Raphson iteration on some data I read in from a file. I use the following function in my python program.
def newton_raphson(r1, r2):
guess1 = 2 * numpy.log(2) / (numpy.pi() * (r1 + r2))
I call this function as so:
if answer == "f": # if data is in file
fileName = input("What is the name of the file you want to open?")
dataArray = extract_data_from_file(fileName)
resistivityArray = []
for i in range(0, len(dataArray[0])):
resistivity_point = newton_raphson(dataArray[0][i], dataArray[1][i])
resistivityArray += [resistivity_point]
On running the program and entering my file, this returns `TypeError: 'float' object is not callable'. Everything I've read online suggests this is due to missing an operator somewhere in my code, but I can't see where I have. Why do I keep getting this error and how do I avoid it?
numpy.pi is not a function, it is a constant:
>>> import numpy
>>> numpy.pi
3.141592653589793
Remove the () call from it:
def newton_raphson(r1, r2):
guess1 = 2 * numpy.log(2) / (numpy.pi * (r1 + r2))
as that is causing your error:
>>> numpy.pi()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable