[Tutor] wordcount.py query
Dave Angel
d at davea.name
Thu Jun 28 02:17:21 CEST 2012
On 06/27/2012 07:59 PM, Imran Javeed wrote:
> Hello
>
> I have attempted the wordcount.py exercise and am trying to understand the
> logic behind the code.
>
> Im trying to replay the code on the python cmd line but keep getting this
> error
>
>>>> w_count[string] = w_count[string] + 1
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: cannot concatenate 'str' and 'int' objects
>
>
> I was trying to recreate the scenario whereby the dict value is incremented
> by 1 as in the following code, it works in the python script but not when i
> manually create & populate the dict value & increment it on the pythin cmd
> line, can you please explain why?
>
> def count_words(filename):
> w_count = {}
> file = open(filename, 'rU')
> for line in file:
> w = line.split()
> for string in w:
> string = string.lower()
> if not string in w_count:
> w_count[string] = 1
> else:*
> ** w_count[string] = w_count[string] + 1*
> file.close()
> return w_count
>
>
Clearly you typed more at the interpreter prompt than that one line. So
in one of your previous lines you must have set w_count[string] to a
string value, rather than to the integer 1.
--
DaveA
More information about the Tutor
mailing list