Home > Backend Development > Python Tutorial > Python实现统计单词出现的个数

Python实现统计单词出现的个数

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-10 15:11:22
Original
4397 people have browsed it

最近在看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]))
Copy after login

假设文件名是 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. 最后打印出结果。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template