How to set value of parent argument to child method? - python

I have a Paragraph class:
from googletrans import Translator
class Paragraph:
def __init__(self, text, origin_lang='en'):
self.text = text
self.origin_lang = origin_lang
def translate(self, dest_lang='ne'):
translator = Translator()
translation = translator.translate(text = self.text,
dest=dest_lang)
return translation.text
I made a subclass out of it:
class FileParagraph(Paragraph):
def __init__(self, filepath):
super().__init__(text=self.get_from_file())
self.filepath = filepath
def get_from_file(self):
with open(self.filepath) as file:
return file.read()
While Paragraph got the text directly as argument, the subclass generates the text from the get_from_file method.
However, I cannot seem to call the inherited translate method:
fp = FileParagraph("sample.txt")
print(fp.translate(dest_lang='de'))
That throws an error:
Traceback (most recent call last):
File "C:/main.py", line 66, in <module>
fp = FileParagraph("sample.txt")
File "C:/main.py", line 20, in __init__
super().__init__(text=self.get_from_file())
File "C:/main.py", line 25, in get_from_file
with open(self.filepath) as file:
AttributeError: 'FileParagraph' object has no attribute 'filepath'
One solution is to change the subclass init to:
def __init__(self, filepath):
self.filepath = filepath
self.text = self.get_from_file()
However, that means removing the initialization of super(). Is there another solution without having to remove super().__init__?
Or is this not even the case to make use of inheritance?

The error comes from calling the get_from_file method, which relies on self.filepath, before self.filepath is set. Simply changing the order of the two lines in __init__ fixes this
class FileParagraph(Paragraph):
def __init__(self, filepath):
# set member variable first
self.filepath = filepath
# then call super's init
super().__init__(text=self.get_from_file())
def get_from_file(self):
with open(self.filepath) as file:
return file.read()

i think that you should also give a value for the filepath while creating the object here
fp = FileParagraph("sample.txt")
you should also input a value for the filepath along with text
eg
fp = FileParagraph(text = "sample.txt", filepath = " ")

Related

How do I process numerous files using numerous regex conditions?

I want to process the cna and linear_cna files by reading only lines that do not contain either Hugo_Symbol or -01.
import os
import re
class DataProcessing:
def __init__(self, data):
self.line = [line.rstrip('\n') for line in data]
self.data = data
def read_data(self):
with open(self.data):
pass
return self.line
def read_cna(self):
# In cna and linear_cna files, skip lines that either begin with "Hugo_Symbol" or "-01"
for lines in self.line:
cna_lines = [lines for l in cna if not re.findall(r"^(Hugo_Symbol|[-01])", l)]
return cna_lines
...continue...
dp_cna = DataProcessing("data_cna.txt")
dp_linear_cna = DataProcessing("data_linear_cna.txt")
dp_cna.read_data()
dp_linear_cna.read_data()
Traceback:
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/testing/main.py", line 24, in <module>
cna = DataProcessing.read_data("data_cna.txt")
File "C:/Users/User/PycharmProjects/testing/main.py", line 14, in read_data
with open(self.data) as f:
AttributeError: 'str' object has no attribute 'data'
The right way to use your class consists of two steps.
Step 1: Create an instance of DataProcessing by invoking __init__. You do this by declaring dp = DataProcessing("data_cna.txt"). You can replace dp with any name you want.
Now dp is an instance of DataProcessing. Its data field is set to "DataProcessing". In other words, dp remembers the name of the file.
Step 2: Call read_data on dp. Note that read_data has only one parameter, namely self, which should not be passed as an argument, meaning it takes no arguments. Therefore, the right way to call read_data is just read_data(). To call read_data on dp you do dp.read_data().

Write a self-defined class type data to excel using xlsxwriter TypeError: Unsupported type <class '__main__.node'> in write()

I am writing data with self-defined type to an excel file by using xlsxwriter, but got an error:
TypeError: Unsupported type <class '__main__.node'> in write()
Code:
import xlsxwriter
class node(object):
def __init__(self, value):
self.value = value
self.children = []
def __repr__(self, level=0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.__repr__(level+1)
return ret
def add(self, nod):
self.children.append(node(nod))
leaf_1 = ['AA','BB','CC','DD']
workbook = xlsxwriter.Workbook('print_def.xlsx')
worksheet = workbook.add_worksheet()
tree = parent = node(leaf_1[0]) #### code 1
parent.add(leaf_1[1])
parent.add(leaf_1[2])
print(tree)
worksheet.write(1, 0, tree)
Expected result(put the tree with indent spaces in the specific cell):
Question:
Does anyone have experience on this error? or suggestion? Thanks in advance!
Update:
I added the following part after the print(tree), instead of using worksheet.write(1, 0, tree)
def write_node(worksheet, row, col, tree, format = None):
return worksheet.write_string(row, col, str(tree), format)
worksheet.add_write_handler(tree.children, write_node)
# worksheet.add_write_handler(tree.node, write_node)
worksheet.write('A1', tree)
But, got error as follows:
Traceback (most recent call last):
File "/Users.../pythonProject/2021-05-16.py", line 137, in <module>
worksheet.add_write_handler(tree.children, write_node)
File "/Users.../pythonProject/lib/python3.9/site-packages/xlsxwriter/worksheet.py", line 1365, in add_write_handler
self.write_handlers[user_type] = user_function
TypeError: unhashable type: 'list'
XlsxWriter doesn't write arbitrary data types so the __repr__ in your class is ignored.
If you want to write user defined types you will need to use the Xlsxwriter add_write_handler() mechanism. See the XlsxWriter documentation on Writing user defined types. It has a detailed explanation and several examples.
Also note, you should first verify that you can get Excel to display the data in the way you want it. You will need to add a textwrap format as a minimum.
Update. Here is a small working example based on your code:
import xlsxwriter
class node(object):
def __init__(self, value):
self.value = value
self.children = []
def __repr__(self, level=0):
ret = " " * level + repr(self.value) + "\n"
for child in self.children:
ret += child.__repr__(level+1)
return ret
def add(self, nod):
self.children.append(node(nod))
def write_node(worksheet, row, col, tree, format=None):
return worksheet.write_string(row, col, str(tree), format)
workbook = xlsxwriter.Workbook('print_def.xlsx')
worksheet = workbook.add_worksheet()
text_wrap = workbook.add_format({'text_wrap': True})
worksheet.add_write_handler(node, write_node)
leaf_1 = ['AA', 'BB', 'CC', 'DD']
tree = parent = node(leaf_1[0])
parent.add(leaf_1[1])
parent.add(leaf_1[2])
worksheet.write(0, 0, tree, text_wrap)
workbook.close()
Output:
Note, I replaced the "\t" with 4 spaces since that shows up better in Excel. Also, you need to add a text wrap format, as shown.

AttributeError: 'str' object has no attribute 'csv'

I am trying to write a CSV file and I have code to create a document with a header file this code will take inputs to write to that same file.
class CSVFile:
def __init__(self, doctitle):
#creates the physical doc on the disk
#creates the header row in the .csv file
self.doctitle = doctitle
self.f = open(doctitle + ".csv", 'w+')
self.f.write("vianumber, innerdiameter, outerdiamter, ratio \n")
self.closedoc()
return
def appendrow(self, doctitle, vianumber, innerdiameter, outerdiamter, ratio):
#called for each measured via
self.f = open(doctitle + ".csv", 'a+')
self.f.write(vianumber, innerdiameter, outerdiamter, ratio)
self.closedoc()
return
def closedoc(self):
#filize the document
self.f.close()
return
The error message I get is the following:
CSVFile.appendrow("", "test", 2, 3, 4, 5)
Traceback (most recent call last):
File "<ipython-input-21-07d259b7d2fa>", line 1, in <module>
CSVFile.appendrow("", "test", 2, 3, 4, 5)
File "C:/Users/Brook/Desktop/Senior Design/CSV file script.py", line 23, in appendrow
self.f = open(doctitle + ".csv", 'a+')
AttributeError: 'str' object has no attribute 'f'
This is because you are not instantiating an object. Your call is CSVFile.appendrow("", "test", 2, 3, 4, 5).
Essentially, it means that for the self parameter of appendrow you are passing an empty string argument "".
Try something along lines of CSVFile("test").appendrow("test", 2, 3, 4, 5)
You have an error in the self.f.write call in your code as well, but I will let you fix that.
Your class and the way you use it have a lot of issues, such as:
You do not use the stored file name.
You do not use the standard CSV writer.
You do not use with blocks.
You do not create a class object.
You create unnecessary object attributes.
You pass the self parameter to an object method.
Here is an improved version of your code.
import csv
class CSVFile:
def __init__(self, doctitle):
self.doctitle = doctitle + ".csv"
with open(doctitle, 'w+') as f:
writer = csv.writer(f)
writer.writerow(["vianumber", "innerdiameter",
"outerdiamter", "ratio"])
def appendrow(self, vianumber, innerdiameter, outerdiamter, ratio):
#called for each measured via
with open(self.doctitle, 'a+') as f:
writer = csv.writer(f)
writer.writerow([vianumber, innerdiameter, outerdiamter, ratio])
#def closedoc(self): -- Not needed!
#filize the document
mycsv = CSVFile("foo")
mycsv.appendrow(2,3,4,5)

Object orientation: error with method in Python

I've made a Python programm with a interface that receives the name of the file and a numerical data. When I create methods to manipulate filename, directory, among others, it returns an error.
I believe the error comes with object orientation. How can I solve this?
I've divided the program in two parts: one to solve my problem (no object orientation) and another to receive user data.
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1541, in __call__
return self.func(*args)
File "teste.py", line 60, in verificaSenha
if (Procura_nome(nome_arq) == 1):
NameError: global name 'Procura_nome' is not defined
The complete code: https://pastebin.com/Br6JAcuR
Problematic method:
def Procura_nome(nome_arq):
dir = Percorre_dir_entrada()
arquivo = dir + dir[2] + nome_arq + + ".shp"
os.path.isfile(nome_arq)
try:
with open(arquivo, 'r') as f:
return 1
except IOError:
return 0
All python method class must have self param as first argument, this argument refers to the instance of your class, also when using class methods and attributs inside your class you should refer to them with self.
You probably need to add self to all your method class in your file.
You also need to remove one '+' on the 3rd line.
def Procura_nome(self, nome_arq):
dir = self.Percorre_dir_entrada()
arquivo = dir + dir[2] + nome_arq + ".shp"
os.path.isfile(nome_arq)
try:
with open(arquivo, 'r') as f:
return 1
except IOError:
return 0
Your Percorre_dir_entrada and Percorre_dir_saida function are doing exactly the same thing on different files, you should think about doing a generic version who take the file name as param like so :
def Percorre_dir(self, file_name):
achou = 0
dirlist = os.listdir(".")
for i in dirlist:
filename = os.path.abspath(i)
if((filename.find(file_name)) != -1):
achou = 1
return filename
if(achou == 0):
return 0
then call it :
Percorre_dir("Saida")
Percorre_dir("Entrada")

Passing a file to a class

First time writing a class here and I need a little help.
I've been trying to write a class in which the first takes a tab-delimited csv file and outputs a list of dictionaries. Each of the keys in the dictionary is a column title in the csv.
So far, this is what my class looks like:
import csv
class consolidate(object):
def __init__(self, file):
self.file = file
def create_master_list(self):
with(open(self,'rU')) as f:
f_d = csv.DictReader(f, delimiter = '\t')
m_l = []
for d in f_d:
m_l.append(d)
return m_l
When I try to pass it a file, as follows:
c = consolidate()
a = c.create_master_list('Abilities.txt')
I get the following error:
TypeError: __init__() takes exactly 2 arguments (1 given)
I know that what I want to pass a file argument to the create_master_list function, but I'm unsure what the right syntax to do this is.
I've tried self.file and file as arguments, and both do not work as well.
Thanks!
Problem
You did not supply second argument for __init__():
class consolidate(object):
def __init__(self, file):
self.file = file
# rest of the code
while you are instantiating it like this:
c = consolidate()
Solution
This should work. Change class definition to this:
import csv
class consolidate(object):
def __init__(self, filename):
self.filename = filename
def create_master_list(self):
with open(self.filename, 'rU') as f:
f_d = csv.DictReader(f, delimiter='\t')
m_l = []
for d in f_d:
m_l.append(d)
return m_l
and then use it like this:
c = consolidate('Abilities.txt')
a = c.create_master_list()
This is one way of achieving the fix.
Note: I also changed the naming (self.file suggested it is file object, while it actually is a file name, thus self.filename). Also keep in mind that the path is relative to from where you execute the script.
You should pass the file as a parameter to __init__.
c = consolidate ('abilities.txt')
Then inside create_master_list you should open self.file.
with (open (self.file, 'rU') ) as f:
Now you can call
a = c.create_master_list ()
That's because your __init__ method of consolidate needs an argument for file:
def __init__(self, file):
but you don't give it anything:
c = consolidate()
To fix this problem, change your class like so:
import csv
# I capitalized the name of this class because that is convention
class Consolidate(object):
def __init__(self, file):
self.file = file
def create_master_list(self):
# 'self' is the instance of 'Consolidate'
# you want to open 'self.file' instead, which is the file
with(open(self.file,'rU')) as f:
f_d = csv.DictReader(f, delimiter = '\t')
m_l = []
for d in f_d:
m_l.append(d)
return m_l
and then use it like this:
c = Consolidate('Abilities.txt')
a = c.create_master_list()

Categories

Resources