Here's one way, can surely be optimized:
* paragraph = "This paragraph contains words once, more than once, and
possibly not at all either. Figure that one out. "
para = paragraph.strip('.').strip(',').strip().split()
wordDict = {}
for word in para:
word = word.strip('.').strip(',')
if wordDict.has_key(word):
wordDict[word] += 1
else:
wordDict[word] = 1*
* print wordDict
*
-Mario
On Wed, Jun 20, 2012 at 1:26 PM, Alan Gauld <[email protected]>wrote:
> On 20/06/12 16:20, Martin A. Brown wrote:
>
> : should have written something like "counting how many times each
>> : word occured" insted of "counting words".
>>
>> You might like to try out collections.defaultdict().
>>
>
> Even a standard dict would simplify the code dramatically.
> The defaultdict does suit this case better though.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
>
> ______________________________**_________________
> Tutor maillist - [email protected]
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor