Аргумент 2: <класс 'TypeError'>: неверный тип
У меня есть приложение Django на языке Python.
И я хочу отфильтровать некоторые подтексты из извлеченного текста.
Вот как выглядит мой views.py:
class ReadingFile(View):
def get(self, request):
form = ProfileForm()
return render(request, "main/create_profile.html", {
"form": form
})
def post(self, request):
submitted_form = ProfileForm(request.POST, request.FILES)
content = ''
if submitted_form.is_valid():
uploadfile = UploadFile(image=request.FILES["upload_file"])
name_of_file = str(request.FILES['upload_file'])
uploadfile.save()
with open(os.path.join(settings.MEDIA_ROOT,
f"{uploadfile.image}"), 'r') as f:
print("Now its type is ", type(name_of_file))
print(uploadfile.image.path)
# reading PDF file
if uploadfile.image.path.endswith('.pdf'):
content = ExtractingTextFromFile.filterAnanas(self)
# ENDING Reading pdf file
else:
with open(os.path.join(settings.MEDIA_ROOT, uploadfile.image.path)) as f:
content = f.read()
return render(request, "main/create_profile.html", {
'form': ProfileForm(),
"content": content
})
return render(request, "main/create_profile.html", {
"form": submitted_form,
})
и это класс: ExtractingTextFromFile.py
class ExtractingTextFromFile:
def extract_text_from_image(filename):
text_factuur_verdi = []
pdf_file = wi(filename=filename, resolution=300)
all_images = pdf_file.convert('jpeg')
for image in all_images.sequence:
image = wi(image=image)
image = image.make_blob('jpeg')
image = Image.open(io.BytesIO(image))
text = pytesseract.image_to_string(image, lang='eng')
text_factuur_verdi.append(text)
return text_factuur_verdi
def __init__(self ):
# class variables:
self.apples_royal_gala = 'Appels Royal Gala 13kg 60/65 Generica PL Klasse I'
self.ananas_crownless = 'Ananas Crownless 14kg 10 Sweet CR Klasse I'
self.peen_waspeen = 'Peen Waspeen 14x1lkg 200-400 Generica BE Klasse I'
self.tex_factuur_verdi = []
def make_pattern(substr):
return r"(?<=" + substr + r").*?(?P<number>[0-9,.]*)\n"
def filterAnanas(self):
self.get_text_from_image()
return re.findall(self.make_pattern(self.ananas_crownless), self.text_factuur_verdi[0])
и теперь я просто пытаюсь вызвать метод:
def filterAnanas(self):
из файла views.py. То есть вот эта строка в файле views.py:
content = ExtractingTextFromFile.filterAnanas(self)
Но затем я получаю эту ошибку:
'ReadingFile' object has no attribute 'get_text_from_image'
Мой вопрос: как я могу вызвать метод: filterAnanas из файла views.py?
Спасибо
Так что сейчас у меня это выглядит так:
def filterAnanas(self):
self.extract_text_from_image()
return re.findall(self.make_pattern(self.ananas_crownless), self.text_factuur_verdi[0])
and in views.py:
extract_instance = ExtractingTextFromFile()
content = extract_instance.filterAnanas()
Затем я получаю эту ошибку:
ArgumentError at /
argument 2: <class 'TypeError'>: wrong type
У меня есть:
def filterAnanas(self, file_name):
self.extract_text_from_image(file_name)
return re.findall(self.make_pattern(self.ananas_crownless), self.text_factuur_verdi[0])
тогда я получаю следующее:
ExtractingTextFromFile.extract_text_from_image() takes 1 positional argument but 2 were given
Вам необходимо инициализировать класс перед вызовом его методов.
import ExtractingTextFromFile # You need to make sure the class properly imported
class ReadingFile(View):
def get(self, request):
... your code...
def post(self, request):
extract_instance = ExtractingTextFromFile() # Initialise the class here
... your code...
return_value = extract_instance.filterAnanas(file_name) # Call method here
Поскольку вы не делаете никакого наследования для ExtractingTextFromFile
класса, убедитесь, что там будет get_text_from_image
метод.
class ExtractingTextFromFile:
def extract_text_from_image(self, filename):
self.text_factuur_verdi = []
... your code ...
# no need to return from this method
def filterAnanas(self, file_name):
self.extract_text_from_image(file_name)
return re.findall(self.make_pattern(self.ananas_crownless), self.text_factuur_verdi[0])
Я не вижу объявления метода get_text_from_image()
, убедитесь, что метод будет.
Когда вы хотите вызвать метод из класса, вы не должны использовать self
self используется внутри класса для передачи объекта как экземпляра вы можете вызвать его таким образом
content = ExtractingTextFromFile.filterAnanas()