简体   繁体   English

大写字母单词计数python

[英]Capital letter word count python

Right now my code prints how many times every word is used in the txt file. 现在,我的代码打印出txt文件中每个单词使用了多少次。 I'm trying to get it to ONLY print the top 3 words used with capital letters within the txt file... 我正在尝试使其仅打印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)

First you want to limit your result to only capitalized words using str.istitle() : 首先,您想使用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)

Then sort the results using sorted() and print out the first three: 然后使用sorted() 对结果进行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]

In Collections there's a Counter class. Collections有一个Counter类。 https://docs.python.org/2/library/collections.html . https://docs.python.org/2/library/collections.html

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM