Question: So my function should open a file and count the word length and give the output. For example,

many('sample.txt')

Words of length 1: 2

Words of length 2: 6

Words of length 3: 7

Words of length 4: 6

My sample.txt file contains:
This is a test file. How many words are of length one?
How many words are of length three? We should figure it out!
Can a function do this?

My coding so far,

```
def many(fname): infile = open(fname,'r')
text = infile.read()
infile.close()
L = text.split()
L.sort
for item in L:
    if item == 1:
        print('Words of length 1:', L.count(item))

```

Can anyone tell me what I'm doing wrong. I call the function nothing happens. It's clearly because of my coding but I don't know where to go from here. Any help would be nice, thanks.

Answer: 
Maybe also this: 

```
>>> s
'This is a test file. How many words are of length one? How many words are of length three? We should figure it out! Can a function do this?'
>>> {x:[len([c for c in w ]) for w in s.split()].count(x) for x in [len([c for c in w ]) for w in s.split()] }
{1: 2, 2: 6, 3: 5, 4: 6, 5: 4, 6: 5, 8: 1}

```
The regular expression library might also be helpful, if being somewhat overkill. A simple word matching re might be something like:

```
import re
f = open("sample.txt")
text = f.read()
words = re.findall("\w+", text)

```

Words is then a list of... words :)

This however will not properly match words like 'isn't' and 'I'm', as \w only matches alphanumerics. In the spirit of this being homework I guess I'll leave that for the interested reader, but Python [Regular Expression](http://docs.python.org/library/re.html "Regular Expressions") documentation is pretty good as a start.

Then my approach for counting these words by length would be something like:

```
occurrence = dict()
for word in words:
    try:
        occurrence[len(word)] = occurrence[len(word)] + 1
    except KeyError:
        occurrence[len(word)] = 1
print occurrence.items()

```

Where a dictionary (occurrence) is used to store the word lengths and their occurrence in your text. The try: and except: keywords deal with the first time we try and store a particular length of word in the dictionary, where in this case the dictionary is not happy at being asked to retrieve something that it has no knowledge of, and the except: picks up the exception that is thrown as a result and stores the first occurrence of that length of word. The last line prints everything in your dictionary.

Hope this helps :)