python—沉默的羔羊之最多單詞


沉默的羔羊 下載地址

鏈接:https://pan.baidu.com/s/14EzwV-Mn5_A27aSVy-XYIw
提取碼:k272

 

描述

附件是《沉默的羔羊》中文版內容,請讀入內容,分詞后輸出長度大於2且最多的單詞。‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬

如果存在多個單詞出現頻率一致,請輸出按照Unicode排序后最大的單詞。‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬

輸入格式

文件‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬

輸出格式

字符串

#第一種方法
import jieba txt = open("沉默的羔羊.txt",encoding="utf-8").read() words = jieba.lcut(txt) counts = {} for word in words: if len(word) <2: #判斷小於2個字的直接跳過 continue else: #大於2個字的進行計算出現次數 counts[word]= counts.get(word,0)+1 items = list(counts.items()) #items提取鍵和值 轉換列表類型 items.sort(key=lambda x:x[1],reverse=True ) #進行出現次數排序
print(items)
print(items[0])
print(items[0][0])
print(type(items[0][0]))

  

 

 

#第二種方法 參考別人的,也是一種思路
總體思路就是把出現的次數進行依次判斷,每出現一個比
上一個數大,就保存,遍歷完得出一個最大的出現次數(maxc)
import jieba
f = open("沉默的羔羊.txt",encoding="utf-8")
words = jieba.lcut(f.read())
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
maxc = 0 #定義一個起始出現數
maxw = ""
for k in counts:
# 每當拿到一個詞時k 就取對應的value值 進行和maxc對比,
# 當兩個條件都成立時,修改maxc的值(也就是出現次數),全部遍歷完,maxc就是最大數
if counts[k] > maxc and len(k) > 2:
maxc = counts[k] #通過key取value值,
maxw = k #通過遍歷得到的key
# if counts[k] == maxc and len(k) > 2 :
if counts[k] == maxc and len(k) > 2 and k > maxw:
maxw = k
print(maxw)

  

 


免責聲明!

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



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