190k views
3 votes
6.13: Word Count

Write a program that prompts the user to input the name of a text file and then outputs the number of words in the file. You can consider a “word” to be any text that is surrounded by whitespace (for example, a space, carriage return, newline) or borders the beginning or end of the file.
Input Notes:There are two input sources in this program: the text file and standard input. The standard input consists of a single word, the name of the text file to be read.

Output Notes (Prompts and Labels): The filename provided in standard input is prompted for with "Enter a file name: " and displayed so that the filename entered is on the same line as the prompt.

The output of the program is a single line of the form: "The file contains N words." where N is the number of words determined by the program.

User Perplexed
by
7.6k points

1 Answer

6 votes

Answer:

import os

def search_file(file_name):

file_name += '.txt' # The code automatically adds the .txt extension, so the user is expected to just pass in the name of the file without extension

for _, __, files in os.walk('.'):

for file in files:

if file_name == file:

return file

raise FileNotFoundError('File not found')

file_name = input('Enter the name of the file without extension > ')

file = search_file(file_name)

with open(file) as open_file:

a = open_file.read()

a = a.split()

print('The file {}.txt contain {} words'.format(file_name, len(a)))

Step-by-step explanation:

The above code is written in Python Programming Language. The first line of code is an import statement that imports the os module which is responsible for operating system's functionality in Python. This module is needed because we will be doing things like file search in the code.

The next thing that was done is that a function called search_file which accepts just a single argument was defined. The purpose of this function is to use the os module imported earlier and search for the existence of the file passed in as the argument. If the file is found, the file is returned else a FileNotFoundError is raised

Immediately after the function, the program expects an input from the user which should be the name of the file without the extension. It is also assumed that the filename passed in is a text file with the .txt extension.

After the program gets the file name from the user via the input function, the function we defined earlier is now called passing the value of the input as the argument to the function.

if file passed in does not exist, the program crashes there with the FileNotFound exception - thanks to the raise FileNotFoundError statement in the function.

However if the file exists, the file is opened and read. The contents of the file is splitted by whitespace. Then we use the Python's len function is use to count the items in the list after the split function is ran.

Finally, we print this to the console using string formatting

User Shubhangi
by
7.6k points