Home > Mobile >  How to properly call one method from another method
How to properly call one method from another method

Time:05-30

How to properly call one method from another in python. I get some data from the AWS S3 bucket after I want to sort this data and write it into a .txt.

import boto3
import string
import json
import collections


def handler(event, context):
    print(f'Event: {event}')

    s3 = boto3.resource('s3')
    bucket = s3.Bucket(event["bucket"])

    for obj in bucket.objects.all():
        key = obj.key
        body = obj.get()['Body'].read()
        b = json.loads(body)
        c = WordCorrection.create_duplicated_words_file(b)
        # WordCorrection.create_duplicated_words_file(WordCorrection.word_frequency(
        #     WordCorrection.correct_words(b)))
        # WordCorrection.spell_words(WordCorrection.dict_spell_words(WordCorrection.unrecognized_words_from_textrtact(b)))

        return c
      


CONFIDENT_LEVEL = 98


class WordCorrection:
    def correct_words(data):
        spell = SpellChecker()
        correct_words_from_amazon = []
        for items in data['Blocks']:
            if items['BlockType'] == "WORD" and items['Confidence'] > CONFIDENT_LEVEL and {items["Text"]} != spell.known([items['Text']]):
                correct_words_from_amazon.append(items['Text'])
        correct_words_from_amazon = [''.join(c for c in s if c not in string.punctuation) for s in
                                     correct_words_from_amazon]

        return correct_words_from_amazon

    def word_frequency(self, correct_words_from_amazon):
        word_counts = collections.Counter(correct_words_from_amazon)
        word_frequency = {}
        for word, count in sorted(word_counts.items()):
            word_frequency.update({word: count})

        return dict(sorted(word_frequency.items(), key=lambda item: item[1], reverse=True))

    def create_duplicated_words_file(word_frequency):
        with open("word_frequency.txt", "w") as filehandle:
            filehandle.write(str(' '.join(word_frequency)))

I was trying to use self but I cannot see a good result, and from the reason I use

WordCorrection.create_duplicated_words_file(WordCorrection.word_frequency(WordCorrection.correct_words(b)))

but I'm in 100% sure that it is not correct, there is another way to call one method from another?

CodePudding user response:

I think your trouble is the result of a misunderstanding about keywords/namespaces for modules vs classes.

Modules:

In python, files are modules so when you are inside of a file, all functions defined up to that point in the file are "in scope." So if I have two functions like this:

def func_foo():
    return "foo"
def func_bar():
    return func_foo()   "bar"

Then func_bar() will return "foobar".

Classes

When you define a class using the class keyword, that defines a new scope/namespace. It is considered proper (although technically not required) to use the word self as the first parameter to an instance method, and this refers to the instance the method is called upon.

For example:

class my_clazz:
    def method_foo(self):
        return "foo" 
    def method_bar(self):
        return self.method_foo()   "bar" 

Then if I have later in the file:

example = my_clazz()
ret_val = example.method_bar()

ret_val will be "foobar"

That said, because I did not really utilize object-oriented programming features in this example, the class definition was largely unnecessary.

Your Issue

So for your issue, it seems like your trouble is caused by what appears to be unnecessarily wrapping your functions inside a class definition. If you got rid of the class definition header and just made all of your functions in the module you would be able to use the calling techniques I used above. For more information on classes in Python I'd recommend reading here.

  • Related