簡體   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