繁体   English   中英

大写字母单词计数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)

首先,您想使用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)

然后使用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]

Collections有一个Counter类。 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