I just started learning OOP and was trying to create a class
but apperently i am not able to call the fuction within function
class WordPic:
def __init__(self,filename,outputname):
self.skipped = ["was","in","the","have","think","these","we","as"]
self.filename = filename
self.outputname = outputname
self.txt_freq = {}
def get_frequancy(self):
with open (self.file_location,"r") as f:
lines = f.read().lower()
splited_lines = lines.split()
for line in splited_lines:
if line not in self.skipped and line.isalpha():
line = line[0].upper() + line[1:]
if line not in self.txt_freq:
self.txt_freq[line] = 1
else:
self.txt_freq[line] += 1
return self.txt_freq
def create_pic(self):
cloud = wordcloud.WordCloud(background_color="white")
cloud.generate_from_frequencies(self.txt_freq)
cloud.to_file("{}.jpg".format(self.outputname))
def create(self):
get_frequancy(self)
create_pic(self)
print("created")
wc = WordPic("try.txt","done")
wc.create()
the error that i encounter is
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [190], in <cell line: 2>()
1 wc= WordPic("try.txt","done")
----> 2 wc.create()
Input In [188], in WordPic.create(self)
28 def create(self):
---> 29 get_frequancy(self)
30 create_pic(self)
31 print("created")
NameError: name 'get_frequancy' is not defined
i am not able to find my way around if anyone can help. thank you
get_frequancy is not a nonlocal variable; it's a class attribute. It has to be accessed as such. (The same goes for create_pic.)
def create(self):
self.get_frequancy()
self.create_pic()
print("created")
(While WordPic.get_frequancy(self) would be sufficient in the example shown, calling instance methods like this runs into problems once you start taking inheritance into account.)
Related
I am wonder whether I can import my class function into my work.
I have put a ipynb file (...\Ipynb Files\job.ipynb) and a py file (...\Ipynb Files\text_modification.py) which contains all functions into a same file path (...\Ipynb Files)
Here is my class
class text_modification():
def __init__(self,text):
self.text=text
#Remove all the emoji used in the text
def emoji_free_text(text):
pattern = re.compile(pattern =
'[' u'\U0001F600-\U0001F64F' # emoticons
u'\U0001F300-\U0001F5FF' # symbols & pictographs
u'\U0001F680-\U0001F6FC' # transport & map symbols
u'\U0001F1E6-\U0001F1FF' # flags (iOS)
u'\U00002500-\U00002BEF' # chinese char
u'\U00002702-\U000027B0'
u'\U000024C2-\U0001F251'
u'\U0001f926-\U0001f937'
u'\U00010000-\U0010ffff'
u'\u2640-\u2642'
u'\u2600-\u2B55'
u'\u23cf'
u'\u23e9'
u'\u231a'
u'\u3030'
u'\ufe0f'
u'\u200a-\u200f'']+',
flags = re.UNICODE)
return pattern.sub(r'',self.text)
# text modification
def delete_repetition(emoji_content, max_times=2):
emoji=list(emoji_content)
emotion=' '.join(emoji_content)
checklist = [lab for lab in dict.fromkeys(emoji) if emoji.count(lab) > 1]
for i in range(len(checklist)):
while(emoji.count(checklist[i]) > max_times):
emoji.remove(checklist[i])
emotion=''.join(emoji)
return emotion
def remove_duplicate_emoji(self,text):
pure_text=emojiFreeText(text)
duplicate_emoji = []
for emo in text:
if emo in (emoji.UNICODE_EMOJI['en'] or emoji.UNICODE_EMOJI['es'] or emoji.UNICODE_EMOJI['pt'] or emoji.UNICODE_EMOJI['it']):
duplicate_emoji.append(emo)
twice_maximum=delete_repetition(duplicate_emoji)
text=pure_text+twice_maximum
return self.text
def free_contact(text):
text=' '.join(re.sub("(#[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",text).split())
return text
def data_processing_auto(text):
emoji_free_text(
remove_duplicate_emoji(text))
And then is my ipynb file
raw_data=pd.read_csv('result.csv',sep=',',header=0,encoding='unicode_escape')
raw_data=raw_data.drop(columns=['Unnamed: 0','source'])
raw_data=raw_data[raw_data['text']!='text'].sort_values(by='created at').reset_index(drop=True)
from text_modification import *
for text in raw_data['text']:
print(text_modification(text).data_processing_auto())
But there is always an error showing that
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[9], line 9
6 from text_modification import *
8 for text in raw_data['text']:
----> 9 print(text_modification(text).emoji_free_text(text))
AttributeError: 'text_modification' object has no attribute 'emoji_free_text'
I have not ideas why the class mentions about raw_data since it never shows within the line,
thanks for anyone who can solve this problem
I am trying to build a Tkinter app which allows you load documents and then analyse them. I must admit I am still getting to grips with object-oriented programming, so apologies if this is a simple answer.
I have built this Class to hold the filepath variables for the rest of the app to use.
class Inputs:
def __init__(self, CV, JS):
self.CV = CV
self.JS = JS
def cv(self, input):
self.CV = input
def js(self, input):
self.JS = input
However everytime I try to pass the following:
b = ‘CV_test.txt’
Inputs.cv(b)
I get the following error.
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3319, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-5-f21fa013f9ae>", line 1, in <module>
Inputs.cv(b)
TypeError: cv() missing 1 required positional argument: 'input'
Is it not possible to pass a filepath as a Class variable?
Supplementary question: Will this approach enable me to call on these variables in other classes at a later date?
Class variables are defined outside of __init__:
class Inputs:
CV = None
JS = None
SELF_JS = None
def cv(self, inp):
Inputs.CV = inp
def js(self, inp):
Inputs.JS = inp
def self_js(self, inp):
# this dont work...
self.SELF_JS = inp
Inputs.CV = 'CV_Test.txt'
my_inputs1 = Inputs()
my_inputs1.js('JS_Test.txt')
my_inputs1.self_js('SELF_Test.txt')
my_inputs2 = Inputs()
print(my_inputs2.JS)
print(my_inputs2.CV)
print(my_inputs2.SELF_JS) # Not available in my_inputs2 !!
Out:
JS_Test.txt
CV_Test.txt
None
I am having issues with self, I have written a class to make a data comparison of two datasets which I am feeding in as a csv - while trying to call this function, I am getting a TypeError.
Here is my class
import csv
import time
import pandas as pd
start_time = time.time()
class compare_files:
def __init__(self, source, target):
self.source = source
self.target = target
def compare_csv(self):
source_file = open(self.source, "r", encoding="utf8")
target_file = open(self.target, "r", encoding="utf8")
csv_reader_source = csv.reader(source_file, delimiter=',')
csv_reader_target = list(csv.reader(target_file, delimiter=','))
columns = []
all_mistakes = []
target_line = 0
for row_source in csv_reader_source:
if target_line == 0:
for i in row_source:
columns.append(i)
target_line = 1
continue
row_target = csv_reader_target[target_line]
target_line += 1
mistakes = []
if len(row_target) != len(row_target):
if len(mistakes) == 0:
mistakes.append(row_source[0])
mistakes.append('number of columns in this row mismatch')
for i in range(len(row_source)):
if row_source[i] != row_target[i]:
if len(mistakes) == 0:
mistakes.append(row_source[0])
mistakes.append(columns[i])
mistakes.append(row_source[i])
mistakes.append(row_target[i])
if len(mistakes) > 0:
all_mistakes.append(mistakes)
return all_mistakes, round(time.time() - start_time, 2)
all_mistakes, time_taken = compare_files.compare_csv(
"source.csv", "target.csv")
for i in all_mistakes:
print(i)
print("Execution time took %s seconds" % (time_taken))
and here is the error, My compare function should accept source and target both, but when I calling compare function it seems it only accepts one argument.
~/Desktop » python3 compar2.py
Traceback (most recent call last):
File "compar2.py", line 70, in <module>
all_mistakes, time_taken = compare_files.compare_csv(
TypeError: compare_csv() takes 1 positional argument but 2 were given
you defined the two parameters in the constructor so you have to call the constructor first like this
com_files = compare_files("source.csv", "target.csv")
then call the compare_csv method without the two parameters like this
all_mistakes, time_taken = com_files.compare_csv()
I try to start a timer to do some file arvchival job. the code is like this:
from threading import Timer
message_archive_dir = "achivedir"
message_archive_format = "zip"
archive_timer = Timer(86400, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
archive_timer.start()
class messageachiver(object):
def __init__(self, **kwargs):
self.message_archive_dir = dir
self.message_archive_format = fmt
def archive(self):
print("message_archive_dir is " + self.message_archive_dir)
print("message_archive_format is " + self.message_archive_format)
print("Archiving trade messages")
I got below error:
Traceback (most recent call last):
File "sa_listener.py", line 43, in <module>
archive_timer = Timer(archive_interval, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
TypeError: __init__() got an unexpected keyword argument 'dir'
I'm not sure why _init_ does not accept **kwargs.
This specific init error is because you are passing multiple variables to the timer class.
In this line:
Timer(86400, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
You are passing the archive function, the dir variable, and the fmt variable to TIMER and not to the messageachiver class. Timer has no named variables for dir and fmt.
So the line should be Timer(86400, messageachiver.archive)
This only partially fixes your problem though. Because you are never actually initializing the class with the variables you need them to have. So before you call timer, you need to initialize the class messageachiver by adding mymessageachiver = messageachiver(dir = message_archive_dir, fmt = message_archive_format)
Also you need to put your class definition before you try to initialize it.
The final code:
from threading import Timer
class messageachiver(object):
def __init__(self, **kwargs):
self.message_archive_dir = kwargs['dir']
self.message_archive_format = kwargs['fmt']
def archive(self):
print("message_archive_dir is " + self.message_archive_dir)
print("message_archive_format is " + self.message_archive_format)
print("Archiving trade messages")
message_archive_dir = "achivedir"
message_archive_format = "zip"
mymessageachiver = messageachiver(dir = message_archive_dir, fmt = message_archive_format)
# That's a huge wait time, try something like 10 for a smaller wait during testing.
archive_timer = Timer(86400, mymessageachiver.archive)
archive_timer.start()
I am trying to implement a factor graph. I would like to read the factor functions from a sperate file. Unfortunately when I read a function from a file just for test I get the error:
eval(lines[0])(1,2,3)
File "<string>", line 1
def f(x0,x1,x2):
^
SyntaxError: invalid syntax
My code is as follows:
class Node:
def __init__(self,name,graph):
self.name = name
self.graph = graph
self.neighbourFactors=[];
class Factor:
def __init__(self,name,neighbours,graph):
self.name = name
self.value = 1
self.graph = graph
self.neighbourNodes=[];
class Graph:
def __init__(self,factorNumber,nodeNumber,factorNeighboursList):
self.factorNumber = factorNumber
self.factors=[Factor(i,factorNeighboursList[i],self) for i in range(factorNumber)]
self.nodes=[Node(i,self) for i in range(nodeNumber)]
factorNumber=0;
for neighbourNodes in factorNeighboursList:
for i in range(len(neighbourNodes)):
self.factors[factorNumber].neighbourNodes.append(self.nodes[int(neighbourNodes[i])]);
self.nodes[int(neighbourNodes[i])].neighbourFactors.append(self.factors[factorNumber])
factorNumber+=1;
def makeGraph(factorNumber,nodeNumber):
factorNeighboursList=[]*factorNumber
f = open('factorNeighboursInput.txt', 'r')
for line in f:
factorNeighboursList.append(line.split())
g=Graph(factorNumber,nodeNumber,factorNeighboursList)
return g
factorNumber=input('Please specify number of Factors:')
nodeNumber=input('Please specify number of Nodes:')
g=makeGraph(factorNumber,nodeNumber)
f = open('factorFunctionInput.txt', 'r')
lines=f.read().split(';')
print lines
eval(lines[0])(1,2,3)
my separate input file for functions is:
def f(x0,x1,x2):
return x0*x1*x2
;
def f(x1):
return x1+1
;
def f(x2):
return x2
;
def f(x3):
return x3+2
;
I think in case of calling eval with multiple line eval function, it fails.
You should use eg.exec instead of eval:solution
Furthermore i think you have to call the functions, the definition doesn't seems enough:
def f(x0,x1,x2):
return x0*x1*x2
f(x0,x1,x2)