考虑以下列表:
['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