大写字母字数

2024-05-29 02:00:30 发布

您现在位置:Python中文网/ 问答频道 /正文

现在,我的代码打印了txt文件中每个单词的使用次数。我试图让它只打印前三个字与大写字母在txt文件中使用。。。你知道吗

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)

Tags: 文件代码intxtforreadopen大写字母
2条回答

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)

首先,您要使用^{}将结果限制为仅大写的单词:

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使用^{}打印出前三个:

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]

相关问题 更多 >

    热门问题