Answer to Question #182946 in Python for Rania

Question #182946


 In a python module, define two functions:

  • 1. A function that finds the number of words contained in a text file. 
  • 2. A function that finds the number of occurrences of a given word in a given file. 
  • • In another file, use these functions by asking the user about the name of the file and the word he/she wants to search for. 
1
Expert's answer
2021-04-18T23:19:36-0400

Answer: Python module called functions

def read_file_content(filename):

    file = open(filename, 'r')
    file_content = file.read();
    words = file_content.split(' ')
    
    return words


def find_number_of_words(filename):
    words = read_file_content(filename)
    return len(words)


def count_occurences(words, word):
    occurences = 0


    for i in range(len(words)):
        if words[i] == word:
            occurences+=1
            
    return occurences

Main module:

import os.path
from os import path


from functions import *


filename = str(input("Enter filename: "))


if path.exists(filename):
    word = str(input("Enter word: "))


    words = read_file_content(filename)
    occurences = count_occurences(words, word)


    if occurences == 0:
        print("Word not found")
    else:
        print("{0} occurences".format(occurences))


else:
    print("Error! File doesn't exist!")

For testing, please create a file called input.txt and put the following text: hello all today is Monday

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS