4

I have a set of string count in the form of set and I want to divide it by some int value.

Example:

 Counter({'dlr': 21, 'said': 18, 'total': 17, 'bankamerica': 13, 'bank': 11, 'analyst': 9, 'prev': 9, 'februari': 8, 'york': 8, 'would': 8, 'price': 8, 'time': 8, 'wheat': 7})

I want to divide it by the some int value so that I will get the word with count divided by that int value.

I am getting TypeError: cannot concatenate 'str' and 'int' objects.

1
  • 1
    This is not a set. It's a collections.counter, which is more like a dictionary. Also, please post the code that is giving you this error Commented Feb 10, 2014 at 18:22

2 Answers 2

4

Build a new counter with a dict comprehension:

>>> counter = Counter({'dlr': 21, 'said': 18, 'total': 17, 'bankamerica': 13, 'bank': 11, 'analyst': 9, 'prev': 9, 'februari': 8, 'york': 8, 'would': 8, 'price': 8, 'time': 8, 'wheat': 7})
>>> counter2 = Counter({k:v/2 for k,v in counter.items()})
>>> counter2
Counter({'dlr': 10, 'said': 9, 'total': 8, 'bankamerica': 6, 'bank': 5, 'would': 4, 'price': 4, 'februari': 4, 'york': 4, 'time': 4, 'prev': 4, 'analyst': 4, 'wheat': 3})

If you didn't want integer division:

>>> from __future__ import division
>>> counter2 = Counter({k:v/2 for k,v in counter.items()})
>>> counter2
Counter({'dlr': 10.5, 'said': 9.0, 'total': 8.5, 'bankamerica': 6.5, 'bank': 5.5, 'prev': 4.5, 'analyst': 4.5, 'would': 4.0, 'price': 4.0, 'februari': 4.0, 'york': 4.0, 'time': 4.0, 'wheat': 3.5})
Sign up to request clarification or add additional context in comments.

3 Comments

Its giving TypeError: 'Counter' object is not callable.
you'll need either from collections import Counter or just use collections.Counter
I did both still its giving error. Will you please explain Counter({k:v/2 for k,v in counter.items()}), so I will find out the solution. I am getting confused in two Counter words.
0

Assuming you meant Counter = {...}:

for key in Counter.keys():
    Counter[key] /= value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.