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
Related
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.)
I am creating a universal text field that can be used in many python turtle projects. I am trying to create an instance of it but I get this error:
>>> import TextField
>>> tf = TextField('None', False)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
tf = TextField('None', False)
TypeError: 'module' object is not callable
>>>
What in a module causes this type of error? I completely wrote this module and I'm getting an error creating an instance of it :( ... What do I need in this module to make it 'callable'? I have tried adding a def __call__(self): but that doesn't affect the problem at all, nor create any errors.
Here is the beginning of the script where the problem is most likely happening:
# Created by SUPERMECHM500 # repl.it
# Edited by cdlane # stackoverflow.com
class TextField:
TextFieldBorderColor = '#0019fc'
TextFieldBGColor = '#000000'
TextFieldTextColor = '#ffffff'
ShiftedDigits = {
'1':'!',
'2':'#',
'3':'#',
'4':'$',
'5':'%',
'6':'^',
'7':'&',
'8':'*',
'9':'(',
'0':')'
}
def __init__(self, command, CanBeEmpty): # Ex. textField = TextField('Execute()', True)
self.CmdOnEnter = command
self.turtle = Turtle()
self.CanBeEmpty = CanBeEmpty
self.turtle.speed('fastest')
self.inp = []
self.FullOutput = ""
self.TextSeparation = 7
self.s = self.TextSeparation
self.key_shiftL = False
......
The module is not the class. If your class TextField is in a module called TextField, then it is referred to as TextField.TextField.
Or change your import to
from TextField import TextField
i try to make a game BUT I can not get the world load to work
fings that cud be gud to no
the var update is for the while loop
the error is in the area wer the block gets pikt and displayd.
class world_load:
def __init__(self, line):
self.type = line[0]
self.x = line[1]
self.y = line[2]
def __str__(self):
return self.type+" "+self.x+" "+self.y
with open(fillName, encoding=encoding) as file:
file.readline()
for line in file.readlines():
line = line.strip()
line = line.split(" ")
w = world_load(line)
world.append(p)
while update:
#input
for event in pygame.event.get():
if event.type == pygame.QUIT:
update = False
dis.fill(sky)
for world_load in world:
wo = world_load.split(" ")
if wo[0] == block_grass:
block_grass(wo[1],wo[2])
it's wos not the hole code
hear is the error fing:
Traceback (most recent call last):
File "C:\Users\Deltagare\Desktop\program\Game\Game.py", line 68, in <module>
wo = world_load.split(" ")
AttributeError: type object 'world_load' has no attribute 'split'
First, it is very hard to read your question because you have used poor grammar and spelling. secondly the .split() function in python is used for strings to split them into an array (list). You might be attempting to split your own class which is not a string and will not work. Or you could be attempting to call the split function within your class (This is what Python thinks you are trying to do) and will also not work because there is no split function. It is unclear what you are asking. I advise you rewrite this question to a higher standard and then people will be more able to help.
This is a GUI I’ve been writing for a script I already have working. What I’m struggling with here is retrieving the information in the textboxes.
Under the definition generate I am able to pop a name off of listx but I am unable to grab the local variable entry from any of the instances of the new_title_box class.
from Tkinter import *
import ttk
boxvar=""
folder=""
listx=[]
count = 1
myrow = 1
class new_title_box:
def __init__(self,name):
global myrow, count, listx
self.entry = StringVar()
self.name = name
self.name = ttk.Entry(mainframe,width=45,textvariable=self.entry)
self.name.grid(column=1,row=myrow+1,sticky=(N,W))
listx.append(name)
print(listx) ## For debugging to insure that it is working correctly, if it gives output it, this part works
myrow = myrow + 1
count=count+1
def make_new(*args):
new_title_box('box'+str(count))
def generate(*args):
global listx, boxvar
while len(listx) > 0:
boxvar=listx.pop(0)
print(boxvar) ## For debugging to insure that it is working correctly, if it gives output it, this part works
folder = boxvar.entry.get() ## Not working here
print(folder) ## For debugging to insure that it is working correctly, if it gives output it, this part works
root = Tk()
root.title("File Maker")
mainframe = ttk.Frame(root, padding = "50 50 50 50")
mainframe.grid(column = 0,row = 0,sticky = (N, W, E, S))
mainframe.columnconfigure(0,weight=1)
mainframe.columnconfigure(0,weight=1)
add_entry = ttk.Button(mainframe,width=20, text = "add entry", command=make_new)
add_entry.grid(column=2,row=2,sticky=(N,W))
add_entry = ttk.Button(mainframe,width=20, text = "make files", command=generate)
add_entry.grid(column=2,row=3,sticky=(N,W))
root.mainloop()
Here's the traceback I'm getting:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter_init_.py", line 1442, in call
return self.func(*args)
File "C:\python\SampAqTkinter.py", line 28, in generate
folder = boxvar.entry ## Not working here
AttributeError: 'str' object has no attribute 'entry'
There are two things that need to be changed to fix the problem you describe:
In the new_title_box.__init__() method change: listx.append(name) to listx.append(self.name)
In the generate() function, change: folder = boxvar.entry.get() to folder = boxvar.get().
You are appending a string to listx, use self.name instead of the local string name
I get a weird error:
Traceback (most recent call last):
File "/remote/us01home15/ldagan/python/add_parallel_definition.py", line 36, in <module>
new_netlist.lines=orig_netlist.add_parallel_extention(cell_name,parallel,int(level))
File "/remote/us01home15/ldagan/python/hspice_netlist.py", line 70, in add_parallel_extention
new_cells_definition=self.gen_parallel_hierarchy(num,self.lines[i])
File "/remote/us01home15/ldagan/python/hspice_netlist.py", line 52, in gen_parallel_hierarchy
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)
NameError: global name 'self' is not defined
From all the tutorials that I have seen, calling a different method from the same class is via self.method_name
It's a script instantiating a class.
The script is:
#!/depot/Python-3.1.1/bin/python3.1
#gets a netlist and a cell name.
#generates a new netlist with the parallel instanciation
import sys
import re
from operator import itemgetter
sys.path.append('/remote/us01home15/ldagan/python/')
from hspice_netlist import hspice_netlist
command="" # initializing argument string
for l in sys.argv:
command=command + " " + "".join(l)
print (len(sys.argv))
print (command)
if (len(sys.argv) <4):
sys.exit("Pleas input original file name & new file name")
orig_netlist=hspice_netlist("file=" + "".join(sys.argv[1])) #reading new netlist
new_netlist=hspice_netlist("") #empty netlist
match=re.search(r"subckt\s*=\s*(\S+)",command)
if (match):
cell_name=match.group(1) #cell to be parallelized name
else:
sys.exit("Please input subckt= <subckt name>")
match=re.search(r"level\s*=\s*(\S+)",command)
if (match):
level=match.group(1) #levels of netlist name
else:
sys.exit("Please input level=<level name>")
match=re.search(r"parallel\s*=\s*(\S+)",command)
if (match):
parallel=match.group(1) #new netlist name
else:
sys.exit("Please input parallel=<parallel name>")
new_netlist.lines=orig_netlist.add_parallel_extention(cell_name,parallel,int(level))
match=re.search(r"outfile\s*=\s*(\S+)",command)
if (match):
output_filename=match.group[1]
outfile=open(output_filename,'w')
outfile.write("".join(new_netlist.lines))
The class code is:
import sys
import re
from collections import defaultdict
class hspice_netlist:
def __init__(self,cmd):
cmd_match=re.search(r"file\s*=\s*(\S+)",cmd)
if (cmd_match):
filename=cmd_match.group(1)
self.infile = open(filename, 'r')
self.lines=self.infile.readlines() #reading the lines
self.infile.close() #closing filehandle
def input_lines(self,lines):
self.lines=lines
def get_subckt_lines(self,name):
gotit=0
ret_lines=[]
find_sub=re.compile("^.sub\S*\s+"+name, re.IGNORECASE)
find_end=re.compile('^.ends', re.IGNORECASE)
for line in self.lines:
if (not gotit):
if (find_sub.search(line)):
gotit=1
ret_lines.append(line)
else:
ret_lines.append(line)
if (find_end.search(line)):
return ret_lines
sys.exit("Could not find the lines for circuit " + name + '\n')
def gen_parallel_inst(num,cell_1st_line):
ret_lines=[] #starting a fresh!!
cell_data=re.search(r"^\S+\s+(\S+)(\s+.*)", cell_1st_line)
cell_name=cell_data.group(1) # got the cell name
new_cell_name=cell_name + '__' + str(num) # new cell name
nodes=cell_data.group(2) # interface
ret_lines.append("".join([".sub ", new_cell_name,nodes,"\n"]))
iter=num
if (not (re.search(r"\s+$",nodes))):
nodes=nodes + ' ' #need a space before the cell name, add if it doesn't exist
while(iter > 0):
line="x" + str(iter) + nodes + cell_name + "\n"
ret_lines.append(line)
iter=iter-1
ret_lines.append(".ends\n") #end of subcircuit definition
return return_lines
def gen_parallel_hierarchy(num_of_parallel,level,cell_1st_line):
'''What that it does: Gets a cell name, then finds that cell's interface definition. It then simply relicates the cell, in parallel, then into hierarchies, ending with new cells' definitions. It is useful for the HSPICE BA issue. It runs recusively. Currently it supports 1 line for interface definition, and no parameters for the cell # this time '''
ret_lines=[]
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)
ret_lines.extend(cell_lines)
if (level>0):
ret_lines.extend(self.gen_parallel_hierarchy(num_of_parallel,level-1,cell_lines[0]))
return ret_lines
def add_parallel_extention(self,cell_name,num,level):
''' Get a cell name + definitions and generates a new netlist '''
i=0
regi=re.compile("^.sub\S*\s+" + cell_name)
m=-1
while ( (i+1 < len(self.lines)) & ( not m )):
i=i+1
m=regi.search(lines[i]) #finding the line
if (not m):
sys.exit("could not find subcircuit definition of " + cell_name + "\n")
new_cells_definition=self.gen_parallel_hierarchy(num,self.lines[i])
i=i-1
ret_lines=self.lines[0:i] # creating return variable, using extend for performance
ret_lines.extend(new_cells_definition)
ret_lines.extend(self.lines[i+1:len(self.lines)])
return ret_lines
#get the cell
#write the level
I am definitely doing something fundamentally wrong, but I don't know what.
Thanks for helping an EE newbe (to Python).
You are missing self in two method declarations.
These
def gen_parallel_hierarchy(num_of_parallel,level,cell_1st_line):
def gen_parallel_inst(num,cell_1st_line):
should be
def gen_parallel_hierarchy(self,num_of_parallel,level,cell_1st_line):
def gen_parallel_inst(self,num,cell_1st_line):
The error happens because you haven't put the self parameter in gen_parallel_hierarchy() but are referring to it in the line which fails:
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)