Skip to main content
 首页 » 编程设计

python之查找列表的公共(public)元素

2025年05月04日9虾米哥

您好,根据 earlier post .

给定以下列表:

['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] 

请您参考如下方法:

#uncomment to produce the word file 
##words = ['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.', ''] 
##open('novel.txt','w').write('\n'.join(words)) 
 
import string 
cap_words = [word.strip(string.punctuation) for word in open('novel.txt').read().split() if word.istitle()] 
##print(cap_words) # debug 
try: 
    from collections import Counter # Python >= 2.7 
    print('Counter') 
    print(Counter(cap_words).most_common(3)) 
except ImportError: 
    print('Normal dict') 
    wordcount= dict() 
    for word in cap_words: 
         wordcount[word] = (wordcount[word] + 1 
                            if word in wordcount 
                            else 1) 
    print(sorted(wordcount.items(), key = lambda x: x[1], reverse = True)[:3]) 

我不明白为什么您要使用“rU”模式保留不同类型的线路终端。正如我在上面编辑的代码中所写的那样,我会使用正常的正常打开。 编辑:你把单词和标点符号放在一起,所以用 strip() 清理掉那些