python學習之文章中單詞出現頻率統計

2021-08-15 15:32:33 字數 1697 閱讀 2630

思路:

統計一篇文章中單詞出現的次數,首先應該知道該文章中,有多少個單詞(去重後),然後再統計單詞在文章中的出現頻率。這裡使用最簡單的方式來實現該功能。

基礎:讀者應該已經掌握python的主要資料結構的用法,——字典、列表、元組與集合。

多數的函式和方法的注釋已經在源**中注釋,這裡對sorted()函式進行一下特別說明。python中對sorted()函式做出的解釋如下所示(可以通過help(function)的方式,獲取對某個函式或方法的幫助):

該解釋的大意是通過sorted(iterable, /, *, key=none, reverse=false)該函式返回乙個公升序的新列表。可以通過key指定排序順序。也可以通過reverse來設定是公升序還是倒序排序。reverse= true降序,reverse=false公升序。

本**通過lambda表示式,以字典中的值為排序的引數。

import string

def

statistics():

"""要注意python在取windows作業系統的格式"""

path = 'c://users/10281/desktop/walden.txt'

"""當直接讀取檔案的時候,可能會遇到編碼格式的問題,這裡使用encoding指定編碼格式為utf-8"""

with

open(path,

'r',

encoding='utf-8') as text:

"""此處使用了list comprehension,該種方式效率較高。

split()方法用於對字串的分片,在預設情況下,為所有的空字元,包括空格、換行(

\n)、製表符(

\t)。

strip()方法用於移除字串頭尾指定的字元(預設為空格)。

set() 函式建立乙個無序不重複元素集,可進行關係測試,刪除重複資料,還可以計算交集、差集、並集等。

count() 方法用於統計字串裡某個字元出現的次數。可選引數為在字串搜尋的開始與結束位置。

"""print(string.punctuation)

words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]

words_index = set(words)

counts_dict =

"""sorted() 函式對所有可迭代的物件進行排序操作。

sort 與 sorted 區別:sort 是應用在 list 上的方法,sorted 可以對所有可迭代的物件進行排序操作。

list 的 sort 方法返回的是對已經存在的列表進行操作,而內建函式 sorted 方法返回的是乙個新的 list,而不是在原來的基礎上進行的操作。

"""for word in

sorted(counts_dict,

key=lambda x: counts_dict[x],

reverse=true):

print('{}--{} times'.format(word, counts_dict[word]))

if __name__ == "__main__":

statistics()

python統計文章單詞次數

題目是這樣的 你有乙個目錄,放了你乙個月的日記,都是 txt,為了避免分詞的問題,假設內容都是英文,請統計出你認為每篇日記最重要的詞。其實就是統計一篇文章出現最多的單詞,但是要去除那些常見的連詞 介詞和謂語動詞等,coding utf 8 import collections import re i...

python 統計文章單詞個數

def gettext txt open article.txt r read txt txt.lower for ch in txt txt.replace ch,return txt hamlettxt gettext words hamlettxt.split counts forword i...

統計文章中單詞出現的次數(續)

符號問題的處理 void filtrate word string word 處理字串中的標點符號 順便把單詞中的大小寫也統一一下,很簡單 void strip cap string word 將單詞中的大寫字母轉化成小寫字母 兩處處理都用到string類的函式find first of 有幾個過載...