Write a program that reads a text file and calculates the average word length and sentence length in that file in python
Code
filename = input("Enter file name: ")# open file in read modef = open(filename, "r")# read the filedata = f.read()# calculate average word length and sentence lengthwords = data.split()sentences = data.split(".")total_words = 0total_sentences = 0for word in words:total_words += len(word)for sentence in sentences:total_sentences += len(sentence)average_word_length = total_words / len(words)average_sentence_length = total_sentences / len(sentences)print(f"Average word length: {average_word_length}")print(f"Average sentence length: {average_sentence_length}")
Output
Enter file name: test.txt
Average word length: 3.5
Average sentence length: 35.0
0 Comments
Post a Comment