如何将我的函数转换为更复杂的 main() 函数?

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

几个小时以来,我一直在尝试将此代码转换为可以使用 main() 函数调用的独立函数,但均未成功

所以这段代码对我有用,但是当我尝试将其变成 if name == "main" 函数时,我保留了出现错误:

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)

我如何将其转换成一个读取文本的函数,另一个计算单词数并通过 main() 函数执行的函数? 类似这样的结构:

def readfile(text)
    return

def wordcount(lines)
    return

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

感谢您的帮助!我希望我没有在问题中犯任何错误......

您可以通过将打开的文件代码编写为来节省一些代码行:

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

整个程序可能如下所示:

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()
text = ''

def readfile(text)
    filename = 'some_text.text'
    file = open(filename, 'r')
    text = file.read()
    file.close()
    return

def wordcount()
    import string 
    text = text.lower()  
    word = text.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()
    readfile()
    wordcount()
    
main()