Python實現統計單詞出現的個數

來源:互聯網
上載者:User

Python實現統計單詞出現的個數

   這篇文章主要介紹了Python實現統計單詞出現的個數,本文給出了實現代碼以及使用方法,需要的朋友可以參考下

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

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import sys

import string

#import collections

 

if len(sys.argv) == 1 or sys.argv[1] in {"-h", "--help"}:

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("'{0}' occurs {1} 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. 最後列印出結果。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.