Frequency 頻率統計

2021-08-11 09:04:53 字數 1992 閱讀 7646

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

"""created on fri oct 20 19:16:41 2017

@author: esri

"""import nltk

from nltk import freqdist

# 做個詞庫先

corpus = 'this is my sentence ' \

'this is my life ' \

'this is the day'

# 隨便便tokenize⼀一下

# 顯然, 正如上⽂文提到,

# 這⾥裡里可以根據需要做任何的preprocessing:

# stopwords, lemma, stemming, etc.

tokens = nltk.word_tokenize(corpus)

print(tokens)

# 得到token好的word list

# ['this', 'is', 'my', 'sentence',

# 'this', 'is', 'my', 'life', 'this',

# 'is', 'the', 'day']

# 借用nltk的freqdist統計一下文字出現的頻率

fdist = freqdist(tokens)

print(fdist)

# 它就類似於乙個dict

# 帶上某個單詞, 可以看到它在整個文章中出現的次數

print(fdist['is'])

# 3# 好, 此刻, 我們可以把最常⽤用的50個單詞拿出來

standard_freq_vector = fdist.most_common(50)

size = len(standard_freq_vector)

print(standard_freq_vector)

# [('is', 3), ('this', 3), ('my', 2),

# ('the', 1), ('day', 1), ('sentence', 1),

# ('life', 1)

# func: 按照出現頻率⼤大⼩小, 記錄下每⼀乙個單詞的位置

def position_lookup(v):

res = {}

counter = 0

for word in v:

#print(word[0])

res[word[0]] = counter

counter += 1

return res

# 把標準的單詞位置記錄下來

standard_position_dict = position_lookup(standard_freq_vector)

print(standard_position_dict)

# 得到⼀乙個位置對照表

# # 這時, 如果我們有個新句句⼦子:

sentence = 'this is cool'

# 先新建⼀乙個跟我們的標準vector同樣⼤大⼩小的向量量

freq_vector = [0] * size

# 簡單的preprocessing

tokens = nltk.word_tokenize(sentence)

# 對於這個新句句⼦子⾥裡里的每⼀乙個單詞

for word in tokens:

try:

# 如果在我們的詞庫⾥裡里出現過

# 那麼就在"標準位置"上+1

freq_vector[standard_position_dict[word]] += 1

except keyerror:

# 如果是個新詞

# 就pass掉

continue

print(freq_vector)

# [1, 1, 0, 0, 0, 0, 0]

# 第⼀乙個位置代表 is, 出現了了⼀一次

# 第⼆二個位置代表 this, 出現了了⼀一次

# 後⾯面都⽊木有

資料頻率分布FREQUENCY函式

excel資料頻率分布frequency函式 frequency函式可以一列垂直陣列返回某個區域中資料的頻率分布 單位需要統計一下各工資段的人數,以弄清楚工資分布情況,以往這工作得用上幾天,現在在excel2010中使用frequency函式就可以很快做完,並且沒有出錯的危險frequency函式可...

統計字元頻率

輸入資料有多組,每組佔一行,由乙個n為的整數構成 ytq急著打 沒有告訴你n是多少,只告訴這個數字小於10的1000次方 對於每組輸入資料,輸出一行,對應乙個要求的答案 答案為0 9之間的乙個數字,如果有過個 數字出現次數一樣多的情況,輸出最小的數字 1234567891 11122333 1235...

NLP 統計頻率

引入必要的包 import re from collections import counter方法一 version one defget max value v1 text 統一為小寫字母 text text.lower 返回所有的字母 result re.findall a za z text...