Python Forum
Create a function to find words of certain length
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create a function to find words of certain length
#1
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)
Reply
#2
Read the file, split the words, if len of word == required length. add 1 to a counter variable.
Reply
#3
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  find and group similar words with re? cartonics 4 736 Oct-27-2023, 05:36 PM
Last Post: deanhystad
  Function to count words in a list up to and including Sam Oldman45 15 6,596 Sep-08-2023, 01:10 PM
Last Post: Pedroski55
Bug New to coding, Using the zip() function to create Diret and getting weird results Shagamatula 6 1,446 Apr-09-2023, 02:35 PM
Last Post: Shagamatula
  python create function validation mg24 1 843 Nov-15-2022, 01:57 AM
Last Post: deanhystad
  create my exception to my function korenron 2 791 Nov-09-2022, 01:50 PM
Last Post: korenron
  Create a function for writing to SQL data to csv mg24 4 1,170 Oct-01-2022, 04:30 AM
Last Post: mg24
  Create SQL connection function and validate mg24 1 951 Sep-30-2022, 07:45 PM
Last Post: deanhystad
  how can a function find the name by which it is called? Skaperen 18 3,479 Aug-24-2022, 04:52 PM
Last Post: Skaperen
  Error in find pearson correlation function erneelgupta 1 1,870 Mar-01-2022, 03:41 PM
Last Post: stevendaprano
  Generate a string of words for multiple lists of words in txt files in order. AnicraftPlayz 2 2,814 Aug-11-2021, 03:45 PM
Last Post: jamesaarr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020