IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

统计汉字/英文单词数

我爱正则表达式 2012-09-20 13:58:49 累计浏览 2,920 次
本机暂存

一个简单的程序,统计文本文档中的单词和汉字数,逆序排列(出现频率高的排在最前面)。python实现。

思路

  • 使用正则式 "(?x) (?: [\w-]+  | [\x80-\xff]{3} )"获得utf-8文档中的英文单词和汉字的列表。
  • 使用dictionary来记录每个单词/汉字出现的频率,如果出现过则+1,如果没出现则置1。
  • 将dictionary按照value排序,输出。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#author:         rex
#blog:           http://iregex.org
#filename        counter.py
#created:        Mon Sep 20 21:00:52 2010
#desc:           convert .py file to html with VIM.

import sys
import re
from operator import itemgetter

def readfile(f):
    with file(f,"r") as pFile:
        return pFile.read()
       
def divide(c, regex):
    #the regex below is only valid for utf8 coding
    return regex.findall(c)
   
def update_dict(di,li):
    for i in li:
        if di.has_key(i):
            di[i]+=1
        else:
            di[i]=1
    return di
   
def main():

    #receive files from bash
    files=sys.argv[1:]
   
    #regex compile only once
    regex=re.compile("(?x) (?: [\w-]+  | [\x80-\xff]{3} )")

    dict={}

    #get all words from files
    for f in files:
        words=divide(readfile(f), regex)
        dict=update_dict(dict, words)

    #sort dictionary by value
    #dict is now a list.
    dict=sorted(dict.items(), key=itemgetter(1), reverse=True)

    #output to standard-output
    for i in dict:
        print i[0], i[1]

if __name__=='__main__':
    main()

Tips

由于使用了files=sys.argv[1:] 来接收参数,因此./counter.py file1 file2 ...可以将参数指定的文件的词频累加计算输出。

可以自定义该程序。例如,

  • 使用
    1
    2
    regex=re.compile("(?x) ( [\w-]+  | [\x80-\xff]{3} )")
    words=[w for w in regex.split(line) if w]

    这样得到的列表是包含分隔符在内的单词列表,方便于以后对全文分词再做操作。

  • 以行为单位处理文件,而不是将整个文件读入内存,在处理大文件时可以节约内存。
  • 可以使用这样的正则表达式先对整个文件预处理一下,去掉可能的html tags: content=re.sub(r"<[^>]+","",content),这样的结果对于某些文档更精确。

同分类推荐文章

  1. 对基本有序的序列排序算法 (2026-06-11 17:46:49)
  2. Four Levels Of Customer Understanding (2026-05-22 21:00:00)
  3. 除法的意义 (2026-04-12 20:52:17)

查看更多 算法 文章 →

建议继续学习

  1. perl更新/修改/删除文本文件内容 (累计阅读 10,646)
  2. 腾讯-1亿个数据取前1万大的整数-题解答 (累计阅读 10,071)
  3. AWK 简明教程 (累计阅读 9,365)
  4. 15道使用频率极高的基础算法题 (累计阅读 7,005)
  5. AWK介绍 (累计阅读 6,707)
  6. awk 实例之二维数组 (累计阅读 6,011)
  7. Perl命令行常见用法及技巧 (累计阅读 5,912)
  8. 正则表达式的与或非 (累计阅读 5,868)
  9. IMDB评分排名算法 (累计阅读 5,818)
  10. Java程序员必知的8大排序算法 (累计阅读 5,740)