网络编程 
首页 > 网络编程 > 浏览文章

python实现统计汉字/英文单词数的正则表达式

(编辑:jimmy 日期: 2024/10/10 浏览:3 次 )
思路

"(?x) (?: [\w-]+ | [\x80-\xff]{3} )"获得utf-8文档中的英文单词和汉字的列表。
"codetitle">复制代码 代码如下:
#!/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 ...可以将参数指定的文件的词频累加计算输出。

可以自定义该程序。例如,
"codetitle">复制代码 代码如下:
regex=re.compile("(?x) ( [\w-]+ | [\x80-\xff]{3} )")
words=[w for w in regex.split(line) if w]


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

"<[^>]+","",content),这样的结果对于某些文档更精确。
上一篇:巧解 JavaScript 中的嵌套替换(强大正则)
下一篇:正则表达式学习问答
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。