Jfpec
Jfpec

Reputation: 13

Counting word length and frequency in a text file

I am running Python 3.4.X

I would like to create function which takes a string as input (where the string is the name of a file) and returns a dictionary. The dictionary should have key/value pairs where keys are integers that correspond to word lengths and the values are the number of words that appear in the file with that length. I just really have no idea how to do this and I would greatly appreciate any help with this. Thank you!

I want the final output to look something like this { 3:5, 4:2, 5:1, 8:1, 10:1}

Upvotes: 0

Views: 1130

Answers (2)

Uday
Uday

Reputation: 26

Here is a quick example that you can try. The example assumes that the file read has a new word at each line

def create_dict(name):
  ret = {}
  if name:
    with open(name,'r') as fd:
        for line in fd.readlines():
            line = line.replace("\n","")
            if ret.get(len(line),None) == None:
                ret[len(line)] = 1
            else:
                ret[len(line)] += 1
  return ret

returns {8: 1, 2: 1, 4: 2, 5: 2, 6: 1} for the following inout file data

hello
world
from
python
to
test
scenario

Upvotes: 1

wwii
wwii

Reputation: 23743

If you read through the Tutorial and practice the examples, you will start to get ideas. You will need to open a file, iterate over the words in it, determine the length, if the length is already in the dictionary then add 1 to it, if not make a new key:value pair with the value = 1.

Upvotes: 0

Related Questions