主頁 > 知識庫 > python實(shí)現(xiàn)統(tǒng)計(jì)漢字/英文單詞數(shù)的正則表達(dá)式

python實(shí)現(xiàn)統(tǒng)計(jì)漢字/英文單詞數(shù)的正則表達(dá)式

熱門標(biāo)簽:阿里云 科大訊飛語音識別系統(tǒng) 服務(wù)器配置 Mysql連接數(shù)設(shè)置 Linux服務(wù)器 電子圍欄 銀行業(yè)務(wù) 團(tuán)購網(wǎng)站
思路

•使用正則式 "(?x) (?: [\w-]+ | [\x80-\xff]{3} )"獲得utf-8文檔中的英文單詞和漢字的列表。
•使用dictionary來記錄每個(gè)單詞/漢字出現(xiàn)的頻率,如果出現(xiàn)過則+1,如果沒出現(xiàn)則置1。
•將dictionary按照value排序,輸出。

源碼
復(fù)制代碼 代碼如下:

#!/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:] 來接收參數(shù),因此./counter.py file1 file2 ...可以將參數(shù)指定的文件的詞頻累加計(jì)算輸出。

可以自定義該程序。例如,
•使用
復(fù)制代碼 代碼如下:

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


這樣得到的列表是包含分隔符在內(nèi)的單詞列表,方便于以后對全文分詞再做操作。

•以行為單位處理文件,而不是將整個(gè)文件讀入內(nèi)存,在處理大文件時(shí)可以節(jié)約內(nèi)存。
•可以使用這樣的正則表達(dá)式先對整個(gè)文件預(yù)處理一下,去掉可能的html tags: content=re.sub(r"[^>]+","",content),這樣的結(jié)果對于某些文檔更精確。
您可能感興趣的文章:
  • Python實(shí)現(xiàn)統(tǒng)計(jì)英文單詞個(gè)數(shù)及字符串分割代碼
  • 布同 統(tǒng)計(jì)英文單詞的個(gè)數(shù)的python代碼
  • Python統(tǒng)計(jì)純文本文件中英文單詞出現(xiàn)個(gè)數(shù)的方法總結(jié)【測試可用】
  • Python3實(shí)現(xiàn)統(tǒng)計(jì)單詞表中每個(gè)字母出現(xiàn)頻率的方法示例
  • python 文本單詞提取和詞頻統(tǒng)計(jì)的實(shí)例
  • python實(shí)現(xiàn)字符串中字符分類及個(gè)數(shù)統(tǒng)計(jì)
  • python 統(tǒng)計(jì)數(shù)組中元素出現(xiàn)次數(shù)并進(jìn)行排序的實(shí)例
  • python統(tǒng)計(jì)字母、空格、數(shù)字等字符個(gè)數(shù)的實(shí)例
  • Python實(shí)現(xiàn)統(tǒng)計(jì)英文文章詞頻的方法分析

標(biāo)簽:江蘇 衡水 萍鄉(xiāng) 大理 蚌埠 衢州 棗莊 廣元

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python實(shí)現(xiàn)統(tǒng)計(jì)漢字/英文單詞數(shù)的正則表達(dá)式》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266