python中单词个数_Python实现统计单词出现的个数

最近在看python脚本语言,脚本语言是一种解释性的语言,不需要编译,可以直接用,由解释器来负责解释。python语言很强大,而且写起来很简洁。下面的一个例子就是用python统计单词出现的个数。

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]))

假设文件名是 uniquewo

你可能感兴趣的:(python中单词个数)