Python詞頻統(tǒng)計的兩種方法詳解
更新時間:2021年12月06日 15:04:51 作者:Argonaut_
這篇文章主要為大家介紹了Python詞頻統(tǒng)計,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
統(tǒng)計文件里每個單詞的個數(shù)
思路:
分別統(tǒng)計文檔中的單詞,與出現(xiàn)的次數(shù)
用兩個列表將其保存起來,最后再用zip()函數(shù)連接輸出**
想法成立開始實踐
方法一:
# 導入文件
with open("passage.txt", 'r') as file:
dates = file.readlines()
# 處理
words = []
for i in dates:
words += i.replace("\n", "").split(" ") # 用空字符來代替換行 words +是為了不被覆蓋無+將只有最后一條數(shù)據(jù)
# print(i.replace("\n","").split(" "))
setWords = list(set(words)) # 集合自動去重
num = [] # 統(tǒng)計一個單詞出現(xiàn)的次數(shù)
for k in setWords:
count = 0
for j in words:
if k == j:
count = count + 1
num.append(count)
print(num)
print(setWords)
# 輸出
for x, y in zip(setWords, num): # 將兩個列表用zip結合
print(x + ":" + str(y))、
效果圖:

方法二:
此方法用來字典,較前一個相對簡潔一點
# 導入
with open("passage.txt", 'r') as file:
dates = file.readlines()
# 處理
words = []
for i in dates:
words += i.replace("\n", "").split(" ")
# print(i.replace("\n","").split(" "))
# setWords=list(set(words)) #可以不用這個
print(words)
print("-" * 40)
# print(setWords)
diccount = dict()
for i in words:
if (i not in diccount):
diccount[i] = 1 # 第一遍字典為空 賦值相當于 i=1,i為words里的單詞
# print(diccount)
else:
diccount[i] = diccount[i] + 1 # 等不在里面的全部遍歷一遍賦值就都在里面了,我們再來記數(shù)
print(diccount)
效果圖:

統(tǒng)計的文檔

總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
Python中sorted()函數(shù)之排序的利器詳解
sorted()函數(shù)是Python中的內置函數(shù),用于對可迭代對象進行排序,下面這篇文章主要給大家介紹了關于Python中sorted()函數(shù)之排序的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-08-08
Pandas操作兩個Excel實現(xiàn)數(shù)據(jù)對應行的合并
本文主要介紹了Pandas操作兩個Excel實現(xiàn)數(shù)據(jù)對應行的合并,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-01-01
python+opencv實現(xiàn)移動偵測(幀差法)
這篇文章主要為大家詳細介紹了python+opencv實現(xiàn)移動偵測,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-03-03

