考慮以下列表:
['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']
我想指望有多少次出現每一個以大寫字母開頭的字,並顯示前3名。
我不感興趣的話做不以資本開始。
如果一個單詞出現多次,有時以大寫字母開頭,有時不是,只計算它對大寫字母所做的時間。
這是我的代碼看起來像現在:
words = ""
for word in open('novel.txt', 'rU'):
words += word
words = words.split(' ')
words= list(words)
words = ('\n'.join(words)).split('\n')
word_counter = {}
for word in words:
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
popular_words = sorted(word_counter, key = word_counter.get, reverse = True)
top_3 = popular_words[:3]
matches = []
for i in range(3):
print word_counter[top_3[i]], top_3[i]
爲什麼在使用計數器? (順便說一句,請接受一個答案,如果這對你最有幫助的話)。 – kennytm 2010-08-29 12:41:42
這是功課嗎? – Johnsyweb 2010-08-29 21:44:37
如果從文件中讀取單詞,則此問題頂部的Python列表無關緊要。 – Johnsyweb 2010-08-29 21:45:48