亚洲最大看欧美片,亚洲图揄拍自拍另类图片,欧美精品v国产精品v呦,日本在线精品视频免费

  • 站長(zhǎng)資訊網(wǎng)
    最全最豐富的資訊網(wǎng)站

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

    思路

    •使用正則式 “(?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)的單詞列表,方便于以后對(duì)全文分詞再做操作。

    •以行為單位處理文件,而不是將整個(gè)文件讀入內(nèi)存,在處理大文件時(shí)可以節(jié)約內(nèi)存。
    •可以使用這樣的正則表達(dá)式先對(duì)整個(gè)文件預(yù)處理一下,去掉可能的html tags: content=re.sub(r”<[^>]+”,””,content),這樣的結(jié)果對(duì)于某些文檔更精確。

    贊(0)
    分享到: 更多 (0)
    網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)