Search code examples
pythonprogram-entry-point

how can I translate my function into a more complex main() function?


I've been already trying unsuccessfully for a couple of hours to translate this code into separated functions that I can call with a main() function

so this code works for me but when I try to make it into a if name == "main" function I keep getting errors:

filename = 'some_text.txt'
file = open(filename, 'r')
txt = file.read()
file.close()

def countwords(txt):
    import string 
    txt = txt.lower()  
    word = txt.translate(str.maketrans('', '', string.punctuation)).split()
    count = {}
    for i in word:
      if i in count:
       count[i] += 1
      else: count[i] = 1
    return count 

countwords(txt)

how could I translate this into a function that reads the text, another function that counts the words and execute all through a main() function? similar to this structure:

def readfile(text)
    return

def wordcount(lines)
    return

def main()
    readfile(text)
    wordcount(lines)
    if __name__== "__main__" :
main()

Thanks for the help! I hope I didn't make any errors in the question...


Solution

  • You can save some lines of code by writing your open file code as:

    with open('some_text.txt') as file:
        file.read()
    

    The overall program could look like this:

    def read_file():
        with open('test_file.txt') as file:
            return file.read()
    
    
    def word_count(file):
        import string
        txt = file.lower()
        word = txt.translate(str.maketrans('', '', string.punctuation)).split()
        count = {}
        for i in word:
            if i in count:
                count[i] += 1
            else:
                count[i] = 1
        return count
    
    
    def main():
        wc = word_count(read_file())
        print(wc)
    
    main()