HOME 首頁(yè)
SERVICE 服務(wù)產(chǎn)品
XINMEITI 新媒體代運(yùn)營(yíng)
CASE 服務(wù)案例
NEWS 熱點(diǎn)資訊
ABOUT 關(guān)于我們
CONTACT 聯(lián)系我們
創(chuàng)意嶺
讓品牌有溫度、有情感
專(zhuān)注品牌策劃15年

    如何統(tǒng)計(jì)詞頻(如何統(tǒng)計(jì)詞頻python)

    發(fā)布時(shí)間:2023-03-24 06:16:02     稿源: 創(chuàng)意嶺    閱讀: 1061        問(wèn)大家

    大家好!今天讓創(chuàng)意嶺的小編來(lái)大家介紹下關(guān)于如何統(tǒng)計(jì)詞頻的問(wèn)題,以下是小編對(duì)此問(wèn)題的歸納整理,讓我們一起來(lái)看看吧。

    開(kāi)始之前先推薦一個(gè)非常厲害的Ai人工智能工具,一鍵生成原創(chuàng)文章、方案、文案、工作計(jì)劃、工作報(bào)告、論文、代碼、作文、做題和對(duì)話答疑等等

    只需要輸入關(guān)鍵詞,就能返回你想要的內(nèi)容,越精準(zhǔn),寫(xiě)出的就越詳細(xì),有微信小程序端、在線網(wǎng)頁(yè)版、PC客戶端

    官網(wǎng):https://ai.de1919.com

    創(chuàng)意嶺作為行業(yè)內(nèi)優(yōu)秀企業(yè),服務(wù)客戶遍布全國(guó),網(wǎng)絡(luò)營(yíng)銷(xiāo)相關(guān)業(yè)務(wù)請(qǐng)撥打175-8598-2043,或微信:1454722008

    本文目錄:

    如何統(tǒng)計(jì)詞頻(如何統(tǒng)計(jì)詞頻python)

    一、如何用python實(shí)現(xiàn)英文短文的雙詞頻統(tǒng)計(jì)

    簡(jiǎn)單版:

    #!/usr/bin/env python3

    import re

    import jieba

    from collections import Counter

    fname = 'counttest.txt'

    with open(fname) as f:

        s = f.read()

    pattern = re.compile(r'[a-zA-Z]+-?[a-zA-Z]*')

    english_words = Counter(pattern.findall(s))

    other_words = Counter(jieba.cut(pattern.sub('', s)))

    print('n英文單詞統(tǒng)計(jì)結(jié)果:n'+'-'*17)

    print('n'.join(['{}: {}'.format(i, j) for i, j in english_words.most_common()]))

    print('n中文及符號(hào)統(tǒng)計(jì)結(jié)果:n'+'-'*19)

    print('n'.join(['{}: {}'.format(i, j) for i, j in other_words.most_common()]))

    復(fù)雜版:

    #!/usr/bin/env python

    # -*- coding: utf-8 -*-

    from __future__ import print_function, division, unicode_literals

    import sys, re, time, os, jieba

    from collections import Counter

    from datetime import datetime

    class WordCounter(object):

        def __init__(self, from_file, to_file=None, coding=None, jieba_cut=None):

            '''根據(jù)設(shè)定的進(jìn)程數(shù),把文件from_file分割成大小基本相同,數(shù)量等同與進(jìn)程數(shù)的文件段,

            來(lái)讀取并統(tǒng)計(jì)詞頻,然后把結(jié)果寫(xiě)入to_file中,當(dāng)其為None時(shí)直接打印在終端或命令行上。

            Args:

            @from_file 要讀取的文件

            @to_file 結(jié)果要寫(xiě)入的文件

            @coding 文件的編碼方式,默認(rèn)為采用chardet模塊讀取前1萬(wàn)個(gè)字符來(lái)自動(dòng)判斷

            @jieba_cut 是否啟用結(jié)巴分詞,默認(rèn)為None

            

            How to use:

            w = WordCounter('a.txt', 'b.txt')

            w.run()        

            '''

            if not os.path.isfile(from_file):

                raise Exception('No such file: 文件不存在')

            self.f1 = from_file

            self.filesize = os.path.getsize(from_file)

            self.f2 = to_file

            if coding is None:

                try:

                    import chardet

                except ImportError:

                    os.system('pip install chardet')

                    print('-'*70)

                    import chardet

                with open(from_file, 'rb') as f:    

                    coding = chardet.detect(f.read(10000))['encoding']            

            self.coding = coding

            self._c = [Counter(), Counter()]

            self.jieba = False

            if jieba_cut is not None:                  

                self.jieba = True

                

        def run(self):

            start = time.time()

            if 1:

                self.count_direct(self.f1)          

            if self.f2 not in ['None', 'Null', 'none', 'null', None]:

                with open(self.f2, 'wb') as f:

                    f.write(self.result.encode(self.coding))

            else:

                print('nEnglish words:n' + '-'*15)

                print(self.result)

            cost = '{:.1f}'.format(time.time()-start)

            size = humansize(self.filesize)

            tip = 'nFile size: {}. Cost time: {} seconds'     

    #        print(tip.format(size, cost))

            self.cost = cost + 's'

        def count_direct(self, from_file):

            '''直接把文件內(nèi)容全部讀進(jìn)內(nèi)存并統(tǒng)計(jì)詞頻'''

            start = time.time()

            with open(from_file, 'rb') as f:

                line = f.read()

            for i in range(len(self._c)):

                self._c[i].update(self.parse(line)[i])  

                     

                        

        def parse(self, line):  #解析讀取的文件流

            text = line.decode(self.coding)

            text = re.sub(r'-n', '', text) #考慮同一個(gè)單詞被分割成兩段的情況,刪除行末的-號(hào)

            pattern = re.compile(r'[a-zA-Z]+-?[a-zA-Z]*') #判斷是否為英文單詞

            english_words = pattern.findall(text)

            rest = pattern.sub('', text)        

            ex = Counter(jieba.cut(rest)) if self.jieba else Counter(text)

            return Counter(english_words), ex

            

        def flush(self):  #清空統(tǒng)計(jì)結(jié)果

            self._c = [Counter(), Counter()]

        @property

        def counter(self):  #返回統(tǒng)計(jì)結(jié)果的Counter類(lèi)       

            return self._c

                        

        @property

        def result(self):  #返回統(tǒng)計(jì)結(jié)果的字符串型式,等同于要寫(xiě)入結(jié)果文件的內(nèi)容

            ss = []

            for c in self._c:

                ss.append(['{}: {}'.format(i, j) for i, j in c.most_common()])

            

            tip = 'nn中文及符號(hào)統(tǒng)計(jì)結(jié)果:n'+'-'*15+'n'

            return tip.join(['n'.join(s) for s in ss])

    def humansize(size):

        """將文件的大小轉(zhuǎn)成帶單位的形式

        >>> humansize(1024) == '1 KB'

        True

        >>> humansize(1000) == '1000 B'

        True

        >>> humansize(1024*1024) == '1 M'

        True

        >>> humansize(1024*1024*1024*2) == '2 G'

        True

        """

        units = ['B', 'KB', 'M', 'G', 'T']    

        for unit in units:

            if size < 1024:

                break

            size = size // 1024

        return '{} {}'.format(size, unit)

            

    def main():

        if len(sys.argv) < 2:

            print('Usage: python wordcounter.py from_file to_file')

            exit(1)

        from_file, to_file = sys.argv[1:3]

        args = {'coding' : None, 'jieba_cut': 1}

        for i in sys.argv:

            for k in args:

                if re.search(r'{}=(.+)'.format(k), i):

                    args[k] = re.findall(r'{}=(.+)'.format(k), i)[0]

        w = WordCounter(from_file, to_file, **args)

        w.run()

        

    if __name__ == '__main__':

        import doctest

        doctest.testmod()

        main()

    更復(fù)雜的:如果是比較大的文件,建議采用多進(jìn)程,詳情百度:多進(jìn)程讀取大文件并統(tǒng)計(jì)詞頻 jaket5219999

    二、如何用python對(duì)文章中文分詞并統(tǒng)計(jì)詞頻

    1、全局變量在函數(shù)中使用時(shí)需要加入global聲明

    2、獲取網(wǎng)頁(yè)內(nèi)容存入文件時(shí)的編碼為ascii進(jìn)行正則匹配時(shí)需要decode為GB2312,當(dāng)匹配到的中文寫(xiě)入文件時(shí)需要encode成GB2312寫(xiě)入文件。

    3、中文字符匹配過(guò)濾正則表達(dá)式為ur'[\u4e00-\u9fa5]+',使用findall找到所有的中文字符存入分組

    4、KEY,Value值可以使用dict存儲(chǔ),排序后可以使用list存儲(chǔ)

    5、字符串處理使用split分割,然后使用index截取字符串,判斷哪些是名詞和動(dòng)詞

    6、命令行使用需要導(dǎo)入os,os.system(cmd)

    三、針對(duì)詞語(yǔ)在多個(gè)文件里該怎么使用TF-IDF計(jì)算詞頻?

    TF-idf算法其實(shí)是一種用戶資訊檢索與資訊探勘的常用加權(quán)技術(shù),常常被SEOER們應(yīng)用到,而很多人或許不太知道,其實(shí)最直觀的了解就是“網(wǎng)站關(guān)鍵詞密度”。

    直接切入主題,TF-idf算法到底是如何計(jì)算的:

    公式:

    TF:詞頻

    IDF:逆文本頻率指數(shù)

    TF-IDF=TF*IDF

    我們舉例說(shuō)明,TF詞頻的意思,是指一個(gè)詞出現(xiàn)在頁(yè)面中的次數(shù),如果一篇文章的總詞語(yǔ)數(shù)是200,而“網(wǎng)站優(yōu)化”這個(gè)詞出現(xiàn)了4次,那么這個(gè)詞頻TF=4/200,也就是0.02。

    而IDF也就是很文件頻率,指這個(gè)詞在多少頁(yè)面出現(xiàn)過(guò)計(jì)數(shù)為N,文件總數(shù)計(jì)數(shù)為M,那么IDF=lg(M/N)。假設(shè)“網(wǎng)站優(yōu)化”在2000個(gè)頁(yè)面出現(xiàn),總文件數(shù)為1億,那么文件頻率IDF=lg(100000000/2000)=4.69897,那么計(jì)算最后的TF-IDF=0.02*4.69897=0.0939794。

    這只是一個(gè)判斷一個(gè)頁(yè)面的相關(guān)度的問(wèn)題,而在SEO網(wǎng)站優(yōu)化中,并不只是判斷TF-IDF的值加分,我們需要一個(gè)識(shí)別度高的詞來(lái)為頁(yè)面加分。例如:搜索引擎收錄一萬(wàn)億個(gè)頁(yè)面,應(yīng)該說(shuō)每個(gè)頁(yè)面都會(huì)有“的、是、中、地、得”等等詞,這些高頻詞也叫噪音詞或停止詞,搜索引擎會(huì)去除這些詞,所以這些詞的加分權(quán)重其實(shí)應(yīng)該是0。計(jì)算公式:TF-IDF=log(1萬(wàn)億/一萬(wàn)億)=log1=0。

    其實(shí)在搜索引擎檢索中,計(jì)算權(quán)重的時(shí)候,會(huì)根據(jù)每個(gè)詞分詞來(lái)計(jì)算,例如:“SEO網(wǎng)站優(yōu)化的技巧”這個(gè)詞。

    假設(shè):SEO頁(yè)面檢索數(shù)位2000萬(wàn),網(wǎng)站優(yōu)化的檢索數(shù)為1000萬(wàn),技巧的檢索數(shù)為50000萬(wàn)

    搜索引擎索引總數(shù)假設(shè)為100億。

    SEO在www.ruihess.com這個(gè)網(wǎng)站中頁(yè)面(頁(yè)面總詞數(shù)400)出現(xiàn)8次,網(wǎng)站優(yōu)化出現(xiàn)10次,技巧出現(xiàn)16次。

    那么各自的詞頻

    TF(SEO)=8/400=0.02,

    TF(網(wǎng)站優(yōu)化)=10/400=0.025

    TF(技巧)=20/400=0.04

    TF(的)=上面已近提到,的屬于高頻停止詞,權(quán)重為0。

    那么搜索“SEO網(wǎng)站優(yōu)化的技巧”這個(gè)頁(yè)面的相關(guān)度為:TF(總)=0.02+0.025+0.05=0.095。

    而IDF(SEO)=LOG(10000000000/20000000)=2.69897

    IDF(網(wǎng)站優(yōu)化)= LOG(10000000000/10000000)=3

    IDF(技巧)=log(10000000000/100000000)=1.69897

    這么算下來(lái)之后,每個(gè)詞為搜索“SEO網(wǎng)站優(yōu)化的技巧”為頁(yè)面的權(quán)重和相關(guān)度貢獻(xiàn)的值分別為:

    Tf-idf(seo)=0.02*2.69897=0.0539794

    Tf-dif(網(wǎng)站優(yōu)化)=0.025*3=0.075

    Tf-idf(技巧)=0.04*1.69897=0.0679588

    由此可以看出,雖然技巧出現(xiàn)的頻率更高,但識(shí)別度沒(méi)有SEO和網(wǎng)站優(yōu)化高,所以為頁(yè)面的權(quán)重貢獻(xiàn)度并不是太大。

    一個(gè)詞的預(yù)測(cè)能力也就是識(shí)別度越高,那么這個(gè)詞的權(quán)重越大,反之則越小,看到“網(wǎng)站優(yōu)化“可能你就已經(jīng)基本了解這個(gè)頁(yè)面要講什么,但是看到技巧,你可能還不是太明白頁(yè)面的主題。

    當(dāng)然這支持搜索引擎的算法的一個(gè)點(diǎn),我們還要結(jié)合標(biāo)簽來(lái)實(shí)現(xiàn)權(quán)重的提升,例如H標(biāo)簽,而主關(guān)鍵詞周邊的詞也會(huì)加分,這里周邊是指在一個(gè)標(biāo)簽內(nèi)的例如:SEO網(wǎng)站優(yōu)化的技巧主要是一些搜索引擎優(yōu)化

    四、如何用python實(shí)現(xiàn)英文短文的雙詞頻統(tǒng)計(jì)?

    import re

    from itertools import imap as map

    from collections import Counter

    def parserwords(sentence):

        preword = ''

        result = []

        for word in re.findall('w+', sentence.lower()):

            if preword:

                result.append((preword, word))

            preword = word

        return result

    context = """

    Do you hear the people sing, singing a song of angry men. 

    It is the music of a people, who will not be slaves again, 

    when the beating of your heart echoes the beating of the drums. 

    There is a life about to start when tomorrow comes.

    """

    words = []

    for sentence in map(parserwords, 

            re.split(r'[,.]', context.lower())):

        words.extend(sentence)

    prefixcounter = Counter([word[0] for word in words])

    counter = Counter(words)

    meter = {}

    for pre, post in counter.iterkeys():

        meter[(pre, post)] = 1. * counter[(pre, post)] / prefixcounter[pre]

    result = sorted(meter.iteritems(),

        cmp = lambda a, b: cmp(b[1], a[1]) or cmp(a[0], b[0])

        )

    print result[:5]

    以上就是關(guān)于如何統(tǒng)計(jì)詞頻相關(guān)問(wèn)題的回答。希望能幫到你,如有更多相關(guān)問(wèn)題,您也可以聯(lián)系我們的客服進(jìn)行咨詢(xún),客服也會(huì)為您講解更多精彩的知識(shí)和內(nèi)容。


    推薦閱讀:

    小紅書(shū)怎么付費(fèi)推廣(小紅書(shū)如何推廣自己的內(nèi)容)

    怎么申請(qǐng)導(dǎo)航位置(導(dǎo)航位置如何申請(qǐng))

    微信如何解除手機(jī)號(hào)綁定

    電媒機(jī)排行榜(電媒機(jī)排行榜最新)

    槍械排行榜