-
當前位置:首頁 > 創(chuàng)意學院 > 技術(shù) > 專題列表 > 正文
如何統(tǒng)計詞頻(如何統(tǒng)計詞頻python)
大家好!今天讓創(chuàng)意嶺的小編來大家介紹下關(guān)于如何統(tǒng)計詞頻的問題,以下是小編對此問題的歸納整理,讓我們一起來看看吧。
開始之前先推薦一個非常厲害的Ai人工智能工具,一鍵生成原創(chuàng)文章、方案、文案、工作計劃、工作報告、論文、代碼、作文、做題和對話答疑等等
只需要輸入關(guān)鍵詞,就能返回你想要的內(nèi)容,越精準,寫出的就越詳細,有微信小程序端、在線網(wǎng)頁版、PC客戶端
官網(wǎng):https://ai.de1919.com
創(chuàng)意嶺作為行業(yè)內(nèi)優(yōu)秀企業(yè),服務(wù)客戶遍布全國,網(wǎng)絡(luò)營銷相關(guān)業(yè)務(wù)請撥打175-8598-2043,或微信:1454722008
本文目錄:
一、如何用python實現(xiàn)英文短文的雙詞頻統(tǒng)計
簡單版:
#!/usr/bin/env python3import 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)計結(jié)果:n'+'-'*17)
print('n'.join(['{}: {}'.format(i, j) for i, j in english_words.most_common()]))
print('n中文及符號統(tǒng)計結(jié)果:n'+'-'*19)
print('n'.join(['{}: {}'.format(i, j) for i, j in other_words.most_common()]))
復雜版:
#!/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è)定的進程數(shù),把文件from_file分割成大小基本相同,數(shù)量等同與進程數(shù)的文件段,
來讀取并統(tǒng)計詞頻,然后把結(jié)果寫入to_file中,當其為None時直接打印在終端或命令行上。
Args:
@from_file 要讀取的文件
@to_file 結(jié)果要寫入的文件
@coding 文件的編碼方式,默認為采用chardet模塊讀取前1萬個字符來自動判斷
@jieba_cut 是否啟用結(jié)巴分詞,默認為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)容全部讀進內(nèi)存并統(tǒng)計詞頻'''
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) #考慮同一個單詞被分割成兩段的情況,刪除行末的-號
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)計結(jié)果
self._c = [Counter(), Counter()]
@property
def counter(self): #返回統(tǒng)計結(jié)果的Counter類
return self._c
@property
def result(self): #返回統(tǒng)計結(jié)果的字符串型式,等同于要寫入結(jié)果文件的內(nèi)容
ss = []
for c in self._c:
ss.append(['{}: {}'.format(i, j) for i, j in c.most_common()])
tip = 'nn中文及符號統(tǒng)計結(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()
更復雜的:如果是比較大的文件,建議采用多進程,詳情百度:多進程讀取大文件并統(tǒng)計詞頻 jaket5219999
二、如何用python對文章中文分詞并統(tǒng)計詞頻
1、全局變量在函數(shù)中使用時需要加入global聲明
2、獲取網(wǎng)頁內(nèi)容存入文件時的編碼為ascii進行正則匹配時需要decode為GB2312,當匹配到的中文寫入文件時需要encode成GB2312寫入文件。
3、中文字符匹配過濾正則表達式為ur'[\u4e00-\u9fa5]+',使用findall找到所有的中文字符存入分組
4、KEY,Value值可以使用dict存儲,排序后可以使用list存儲
5、字符串處理使用split分割,然后使用index截取字符串,判斷哪些是名詞和動詞
6、命令行使用需要導入os,os.system(cmd)
三、針對詞語在多個文件里該怎么使用TF-IDF計算詞頻?
TF-idf算法其實是一種用戶資訊檢索與資訊探勘的常用加權(quán)技術(shù),常常被SEOER們應用到,而很多人或許不太知道,其實最直觀的了解就是“網(wǎng)站關(guān)鍵詞密度”。
直接切入主題,TF-idf算法到底是如何計算的:
公式:
TF:詞頻
IDF:逆文本頻率指數(shù)
TF-IDF=TF*IDF
我們舉例說明,TF詞頻的意思,是指一個詞出現(xiàn)在頁面中的次數(shù),如果一篇文章的總詞語數(shù)是200,而“網(wǎng)站優(yōu)化”這個詞出現(xiàn)了4次,那么這個詞頻TF=4/200,也就是0.02。
而IDF也就是很文件頻率,指這個詞在多少頁面出現(xiàn)過計數(shù)為N,文件總數(shù)計數(shù)為M,那么IDF=lg(M/N)。假設(shè)“網(wǎng)站優(yōu)化”在2000個頁面出現(xiàn),總文件數(shù)為1億,那么文件頻率IDF=lg(100000000/2000)=4.69897,那么計算最后的TF-IDF=0.02*4.69897=0.0939794。
這只是一個判斷一個頁面的相關(guān)度的問題,而在SEO網(wǎng)站優(yōu)化中,并不只是判斷TF-IDF的值加分,我們需要一個識別度高的詞來為頁面加分。例如:搜索引擎收錄一萬億個頁面,應該說每個頁面都會有“的、是、中、地、得”等等詞,這些高頻詞也叫噪音詞或停止詞,搜索引擎會去除這些詞,所以這些詞的加分權(quán)重其實應該是0。計算公式:TF-IDF=log(1萬億/一萬億)=log1=0。
其實在搜索引擎檢索中,計算權(quán)重的時候,會根據(jù)每個詞分詞來計算,例如:“SEO網(wǎng)站優(yōu)化的技巧”這個詞。
假設(shè):SEO頁面檢索數(shù)位2000萬,網(wǎng)站優(yōu)化的檢索數(shù)為1000萬,技巧的檢索數(shù)為50000萬
搜索引擎索引總數(shù)假設(shè)為100億。
SEO在www.ruihess.com這個網(wǎng)站中頁面(頁面總詞數(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)化的技巧”這個頁面的相關(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
這么算下來之后,每個詞為搜索“SEO網(wǎng)站優(yōu)化的技巧”為頁面的權(quán)重和相關(guā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)的頻率更高,但識別度沒有SEO和網(wǎng)站優(yōu)化高,所以為頁面的權(quán)重貢獻度并不是太大。
一個詞的預測能力也就是識別度越高,那么這個詞的權(quán)重越大,反之則越小,看到“網(wǎng)站優(yōu)化“可能你就已經(jīng)基本了解這個頁面要講什么,但是看到技巧,你可能還不是太明白頁面的主題。
當然這支持搜索引擎的算法的一個點,我們還要結(jié)合標簽來實現(xiàn)權(quán)重的提升,例如H標簽,而主關(guān)鍵詞周邊的詞也會加分,這里周邊是指在一個標簽內(nèi)的例如:SEO網(wǎng)站優(yōu)化的技巧主要是一些搜索引擎優(yōu)化
四、如何用python實現(xiàn)英文短文的雙詞頻統(tǒng)計?
import refrom 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)計詞頻相關(guān)問題的回答。希望能幫到你,如有更多相關(guān)問題,您也可以聯(lián)系我們的客服進行咨詢,客服也會為您講解更多精彩的知識和內(nèi)容。
推薦閱讀:
問大家
抖音如何開通國外直播權(quán)限?抖音海外直播權(quán)限解決辦法
抖音如何開通韓國直播權(quán)限?抖音怎么開通韓國直播權(quán)限辦法
房山喬遷慶典現(xiàn)場協(xié)助大概收費如何?大佬們請問
濟南有哪家婚姻介紹所類性質(zhì)介紹對象的比較正規(guī)?。渴召M如何?
如何開通抖音海外直播白名單?抖音海外直播權(quán)限解決辦法
如何開通抖音海外直播白名單?抖音海外直播權(quán)限解決辦法
成都做的全面的上市會如何避免踩一些雷?在座的老鄉(xiāng)們急急急
山東濟南婚介服務(wù)機構(gòu)征婚哪家好呢?記得要真實可靠的