2013-12-12 114 views
-2

我有一個名爲'words.txt'的文件,其中包含諸如。 #+=%£%=和我需要通過並計數每個符號,而不允許任何重複,然後打印我的答案。打印時,例如,它應該是這樣的:如何計算Python中的頻率?

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

我知道我需要在這和使用一個for循環,我需要使用一套所以doesnt't允許任何重複,但我會怎麼做? Thanl you

+0

可能重複在Python中的字符串](http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python) – Kamiccolo

+0

你有一個可以在文件中找到的所有符號的列表?或者它只是文件中的隨機符號? – Clutch

回答

0

查找字典。

不想發佈更多,因爲它只會破壞練習。

+0

爲什麼downvote? – RedX

4

一個set不是那麼有用這裏它不具有存儲計數

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

for item in c.items(): 
    print("{} : {}".format(*item)) 
+3

爲什麼你不讓他找到一個解決辦法,因爲它顯然是一個練習? – RedX

1

使用Python字典的地方:[計數的重複字符的

symbols = {} 

for c in string: 
    if c not in symbols: 
    symbols[c] = 0 
    symbols[c] += 1