Home:ALL Converter>Find frequency for a specific word in a given string

Find frequency for a specific word in a given string

Ask Time:2021-07-26T21:09:54         Author:PythonAMS

Json Formatter

I have created some code in Python to find the top frequency word in a string. I am pretty new in Python and ask for your help to see if I could code this better and more effectively. (code below returns the frequency of the specified word). Since I am a beginning Python dev I have the feeling my code is unnecessarily long and could be written much better, only good thing is that the code works. But want to learn how I could do it better. I also don't know if my class WordCounter makes sense with it's attributes....

class WordCounter:
def __init__(self, word, frequency):
    self.word = word
    self.frequency = frequency

# calculate_frequency_for_word should return the frequency of the specified word
def frequency_specific_word(text: str, word: str) -> int:
    lookup_word = word #this contains the specified word to search for
    incoming_string = [word.lower() for word in text.split() if word.isalpha()]
    count = 0 #count is increased when the specified word is found in the string
    i=0 #this is used as counter for the index
    j=0 #the loop will run from j=0 till the length on the incoming_string
    length = len(incoming_string) #checking the length of incoming_string
    while j < length:
        j += 1
        if lookup_word in incoming_string[i]: #Specified word is found, add 1 to count
            count += 1
            incoming_string[i] = incoming_string[i + 1]  #move to next word in incoming string
        else:
            incoming_string[i] #Specified word not found, do nothing
            #print("No," + lookup_word + " not found in List : " + incoming_string[i])
        i += 1

    return count

print("The word 'try' found " +str(WordCounter.frequency_specific_word("Your help is much appreciated, this code could be done much better I think, much much better", "much"))+" times in text\n")

Author:PythonAMS,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/68530493/find-frequency-for-a-specific-word-in-a-given-string
yy