69.1k views
5 votes
Create a program that will ask the user to specify a file in the current directory. The program will count and report the number of lines, words and characters. There are several approaches that can be used. Hint: You may want to consider read(), readlines(), readline(), split() method, and/or a for statement such as 'for line in thisfile' might be helpful. The approach is up to you. It is correct if it works!

User Laptou
by
6.9k points

1 Answer

0 votes

Answer:

Step-by-step explanation:

The following code is written in Python. It is a function that takes in the file directory as an argument, reads the file. Then it counts the lines and words in the file and saves that count in separate variables. Then it loops through the entire file counting the characters, without counting whitespace and newlines breaks. Finally, it prints all of that information out.

def countText(file):

f = open(file, 'r')

text = f.read()

lines = len(text.split('\\'))

words = len(text.split(' '))

characters = 0

for char in text:

if (char != ' ') and (char != '\\'):

characters += 1

print("File Count:")

print("Lines: " + str(lines))

print("Words: " + str(words))

print("Characters: " + str(characters))

Create a program that will ask the user to specify a file in the current directory-example-1