Python 计算txt中的单词和字母数。文件

Python 计算txt中的单词和字母数。文件,python,Python,我是编程初学者,目前面临着简单任务的问题。我需要打印单词,计算特定单词的数量以及txt.file中的字母数量。如果有人能帮助我,我将不胜感激: def main(): file_name = input("Input file. \n") sum_of_letters = 0 number_words = 0 try: words = open(file_name, "r") print("File", file_name ,

我是编程初学者,目前面临着简单任务的问题。我需要打印单词,计算特定单词的数量以及txt.file中的字母数量。如果有人能帮助我,我将不胜感激:

def main():   
    file_name = input("Input file. \n")
    sum_of_letters = 0
    number_words = 0
    try:
        words = open(file_name, "r")
        print("File", file_name ,"includes the following words:")        
        for line in words:
            line = line.rstrip()
            words= line.split()
            for i in words:
                print(i)
                sum_of_letters += len(i)
                number_words += 1
        print("---------------------------------------")
        print("Number of words",number_words ,"ja", sum_of_letters,     "kirjainta.")
        close.words()
    except OSError:
        print("Error observed")

您的代码几乎是正确的,但您使用的是
words
来引用文件以及单行中的单词。我已经更新了下面的代码以使用不同的变量:

def main():   
    file_name = input("Input file. \n")
    sum_of_letters = 0
    number_words = 0
    try:
        words = open(file_name, "r")
        print("File", file_name ,"includes the following words:")        
        for line in words:
            line = line.rstrip()
            words_in_line = line.split()
            for i in words_in_line:
                print(i)
                sum_of_letters += len(i)
                number_words += 1
        print("---------------------------------------")
        print("Number of words",number_words ,"ja", sum_of_letters,     "kirjainta.")
        words.close()
    except OSError:
        print("Error observed")

这个代码怎么了?你有什么错误吗?