python練習題7.1詞頻統計


請編寫程序,對一段英文文本,統計其中所有不同單詞的個數,以及詞頻最大的前10%的單詞。

所謂“單詞”,是指由不超過80個單詞字符組成的連續字符串,但長度超過15的單詞將只截取保留前15個單詞字符。而合法的“單詞字符”為大小寫字母、數字和下划線,其它字符均認為是單詞分隔符。

輸入格式:

輸入給出一段非空文本,最后以符號#結尾。輸入保證存在至少10個不同的單詞。

輸出格式:

在第一行中輸出文本中所有不同單詞的個數。注意“單詞”不區分英文大小寫,例如“PAT”和“pat”被認為是同一個單詞。

隨后按照詞頻遞減的順序,按照詞頻:單詞的格式輸出詞頻最大的前10%的單詞。若有並列,則按遞增字典序輸出。

輸入樣例:

This is a test. The word "this" is the word with the highest frequency. Longlonglonglongword should be cut off, so is considered as the same as longlonglonglonee. But this_8 is different than this, and this, and this...# this line should be ignored. 

 
 
 
         

輸出樣例:(注意:雖然單詞the也出現了4次,但因為我們只要輸出前10%(即23個單詞中的前2個)單詞,而按照字母序,the排第3位,所以不輸出。)

23 5:this 4:is

代碼如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
#sys.stdin 標准輸入
# sys.stdout 標准輸出
# sys.stderr 標准錯誤輸出

s = sys.stdin.read()
strs = s[:s.find('#')]

key = set()
for i in strs:
    if i.isalnum()==False and i!='_':
        key.add(i)
for k in key:
    strs = strs.replace(k,' ')
#去掉空格,全部變小寫,變成列表
strs=strs.rstrip(' ').lower().split() #全部變小寫
counts=dict()
for i in strs:
    k=i[:15] #取前15個字符
    if k not in counts:
        counts[k]=1
    else:
        counts[k]+=1
ans=sorted(counts.items(), key=lambda x:(-x[1], x[0]))
print(len(counts))

for i in range(0,int(0.1*len(counts))): #詞頻最大的前10%
    print(str(ans[i][1])+':'+ans[i][0])

參考課堂的程序,基本上是抄過來的。

越來越寫不動了,理解能力跟不上了。~~~~(>_<)~~~~


讀書和健身總有一個在路上


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM