使用python統計單詞出現的個數

2021-08-29 22:22:03 字數 1138 閱讀 5086

最近在看python指令碼語言,指令碼語言是一種解釋性的語言,不需要編譯,可以直接用,由直譯器來負責解釋。python語言很強大,而且寫起來很簡潔。下面的乙個例子就是用python統計單詞出現的個數。

import sys

import string

#import collections

if len(sys.argv) == 1 or sys.argv[1] in :

print("usage: uniqueword filename_1 filename_2 ... filename_n")

sys.exit()

else:

words = {}

# words = collections.defaultdict(int)

strip = string.whitespace + string.punctuation + string.digits + "\"'"

for filename in sys.argv[1:]:

for line in open(filename):

for word in line.split():

word = word.strip(strip)

if len(word) >= 2:

words[word] = words.get(word, 0) + 1

# words[word] += 1

for word in sorted(words):

print("'' occurs times".format(word,words[word]))

假設檔名是 uniqueword.py,在命令列下輸入: uniqueword.py filename_1 filename_2 ... filename_n中單詞出現的次數可以被統計出來。

第四行和第五行判斷是否有輸入引數,如果輸入引數為空或者為-h, -help,則輸出幫助資訊。

從第七行到第14行是核心部分,逐一開啟引數中指定的檔案,並讀取每一行,再用字串的split方法把讀取的行抽取出乙個乙個的單詞,但單詞長度大於2的時候,把此單詞加入到字典words中。 其中words.get(word, 0)的意思是取出key等於word的value,如果key為空,則把value置為預設值0. 最後列印出結果。

python統計單詞出現次數

統計英文兒歌 twinkle twinkle little star 中,使用到的單詞及其出現次數。要求去除單詞大小寫的影響,不統計標點符號的個數,並按降序輸出。twinkle,twinkle,little star,how i wonder what you are up above the wo...

統計單詞出現的頻率

平時我們在工作的時候需要統計一篇文章或者網頁出現頻率最高的單詞,或者需要統計單詞出現頻率排序。那麼如何完成這個任務了?例如,我們輸入的語句是 hello there this is a test.hello there this was a test,but now it is not.希望得到的公...

統計單詞出現頻率

這裡有乙個大文字,檔案請從 獲取,在解壓後大約有20m 實際比賽時檔案是1.1g 文字中都是英文單詞,空格以及英文的標點符號 句號,逗號,分號,破折號,波浪號,雙引號,問號,單引號,感嘆號 請統計出該文字中最常出現的前10個單詞 不區分大小寫 請注意,在統計中這20個單詞請忽略 the,and,i,...