脚本宝典收集整理的这篇文章主要介绍了python实现统计汉字/英文单词数的正则表达式,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
思路
&
#8226;使用正则式 "(?x) (?: [/w-]+ | [/x80-/xff]{3} )"获得utf-8文档中的英文单词和汉字的列表。
•使用dictionary来记录每个单词/汉字出现的频率,如果出现过则+1,如果没出现则置1。
•将dictionary按照value排序,输出。
源码
#!/usr/bin/
python # -*- coding: utf-8 -*-
#
#author: rex
#
blog: http://iregex.
org #filen
ame counter.py
#created: Mon Sep 20 21:00:52 2010
#desc: convert .py file to ht
ML w
ITh VIM.
import
Sys import re
From operator import itemgetter
def rea
DFile(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 m
ain():
#rec
eive files f
rom bash
files=sys.
argv[1:]
#regex compile only once
regex=re
.COMpile("(?x) (?: [/w-]+ | [/x80-/xff]{3} )")
dict={}
#get all wo
rds 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
...可以将参数指定的文件的词频累加计算输出。
可以自定义该程序。例如,
•使用
regex=re.compile("(?x) ( [/w-]+ | [/x80-/xff]{3} )")
words=[w for w in regex.split(line) if w]
这样得到的列表是包含分隔符在内的单词列表,方便于以后对全文分词再做操作。
•以行为单位处理文件,而不是将整个文件读入内存,在处理大文件时可以节约内存。
•可以使用这样的正则表达式先对整个文件预处理一下,去掉可能的html tags: content=re.s
ub(r"<[^>]+","",content),这样的结果对于某些文档更精确。
脚本宝典总结
以上是脚本宝典为你收集整理的python实现统计汉字/英文单词数的正则表达式全部内容,希望文章能够帮你解决python实现统计汉字/英文单词数的正则表达式所遇到的问题。
如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。