question archive Define a function named wordRank that accepts two arguments: a filename and a string

Define a function named wordRank that accepts two arguments: a filename and a string

Subject:Computer SciencePrice:3.86 Bought11

Define a function named wordRank that accepts two arguments: a filename and a string. The function should return the frequency rank of the word that is passed in (1 for the most frequent word, 2 for the 2nd-most frequent word, etc). If the word is not in the file, wordRank should return False. (5 points)

  • Note 1: wordRank should be case-sensitive
  • Note 2: ignore punctuation (treat punctuation as part of the word; 'them' and 'them.' are two separate words)

 

pur-new-sol

Purchase A New Answer

Custom new solution created by our subject matter experts

GET A QUOTE

Answer Preview

#abc.txt

Hello world Hello there
How, are you world, hello!

 

 

#main.py

def wordRank(filename,string):
  #string for all punctuation marks
  punctuation = '.?,\";(){}[]!:-\''
  
  #define dictionary
  dic = {} 
  
  #set dictionary as strings worsd as dictionary key and frequency of word as value(which is set 0 initially) 
  for i in string.split(' '):
    if i not in dic:
      dic[i] = 0 
  
  #open file and read it
  with open(filename,'r') as file:
    #read file line by line
    for lines in file:
      #declare an empty string for each iteration
      line = ''
      
      #split the line into characters 
      for i in lines:
        #check for punctuation
        if i not in punctuation:
          #update a string without any punctuation
          line += i


      #split the string into words 
      for word in line.split():
        #chekc for word in the string by the user 
        if word in dic:
          #update the frequency of the word 
          dic[word] += 1 


  #check for whether file contain atleast one word same as inputted string 
  for i in dic:
    if(dic[i] != 0):
      #if a single word matched return its frequency 
      return dic 


  #if not even a single word of the inputted string match then return false 
  return False



def main():
  #input file name
  filename = input('Enter file name(as aaa.txt): ') 


  #input string
  string = input('Enter string: ') 


  #calling function and save the return value 
  dic = wordRank(filename,string)


  if(dic != False):
    #print the frequency of word
    for key in dic: 
      print(key,' : ',dic[key]) 


if __name__ == "__main__":
  main()

Please see the attached file for the complete solution

Related Questions