Python Forum

Full Version: Create a function to find words of certain length
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to create a program that reads a txt file and gives me an output of the number of times a word of length x (lets say 5) or longer is used. For example, the txt has "The quick brown fox jumps over the lazy dog", The expected out put is 3. I created a function that finds the number of occurrences of a certain word and the number of words in the file but I don't know how to do this. Thanks
def engr102_word_count():
    num_words = 0   
    with open(name, 'r') as x:
        for line in x:
            words = line.split()
            num_words += len(words)
    x.close()
    file1= open(name, 'r')
    str_list = file1.read()
    count = 0
    N = len(str_list)
    n = len(word)

    for i in range(0,N-n):
        if str_list[i:i + n] == word:
            count += 1
    print("Number of words: ", num_words)
    print("Frequency of your word: ", count)
Read the file, split the words, if len of word == required length. add 1 to a counter variable.
This is a concise way to count words of the required length, but it's probably slow. To shorten it to two lines, I could find the length of the list comprehension and delete the line that assigns a value to the word_list variable.

for line in text_file:
    word_list = [word for word in line.split() if len(word) == required_length]
    counter += len(word_list)