大写字母字数 python

Capital letter word count python

现在我的代码打印了每个单词在 txt 文件中使用了多少次。我试图让它只打印 txt 文件中与大写字母一起使用的前 3 个单词...

file=open("novel.txt","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for a,b in wordcount.items():
    print (b, a)

Collections 中有一个 Counter class。 https://docs.python.org/2/library/collections.html

cnt = Counter([w for w in file.read().split() if w.lower() != w]).most_common(3)

首先,您希望使用 str.istitle():

将结果限制为仅大写单词
file=open("novel.txt","r+")
wordcount={}
for word in file.read().split():
    if word.istitle():
        if word not in wordcount:
            wordcount[word] = 1
        else:
            wordcount[word] += 1
for a,b in wordcount.items():
    print (b, a)

然后sort the results using sorted()并打印出前三个:

file=open("novel.txt","r+")
wordcount={}
for word in file.read().split():
    if word.istitle():
        if word not in wordcount:
            wordcount[word] = 1
        else:
            wordcount[word] += 1

items = sorted(wordcount.items(), key=lambda tup: tup[1], reverse=True) 

for item in items[:3]:
    print item[0], item[1]