-3

I had a file called 'words.txt' which contains things such as. #+=%£%= and i need to go through and count each symbol without allowing any duplicates and then print my answer. for example it should look like this when printed:

# : 1
+ : 1
= : 2
% : 2
£ : 1

I know I need to use a for loop in this and that I need to use a set so It doesnt't allow any duplicates but how would I do it? Thanl you

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • possible duplicate of [Counting repeated characters in a string in Python](http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python) – Kamiccolo Dec 12 '13 at 16:06
  • Do you have a list of all the symbols that could be found in the file? Or is it all just random symbols in the file? – Clutch Dec 12 '13 at 16:07

3 Answers3

4

A set isn't so useful here as it doesn't have a place to store the counts

from collections import Counter
with open("words.txt") as fin:
    c = Counter(fin.read())

for item in c.items():
    print("{} : {}".format(*item))
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

Use python dictionary:

symbols = {}

for c in string:
  if c not in symbols:
    symbols[c] = 0
  symbols[c] += 1
Sash
  • 4,448
  • 1
  • 17
  • 31
0

Look up dictionary.

Don't want to post more as it would only spoil the exercise.

RedX
  • 14,749
  • 1
  • 53
  • 76