溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

字符串中單詞的提取與詞頻統(tǒng)計

發(fā)布時間:2024-10-01 10:06:34 來源:億速云 閱讀:81 作者:小樊 欄目:編程語言

在Python中,我們可以使用split()函數(shù)來提取字符串中的單詞,并使用collections模塊中的Counter類來進(jìn)行詞頻統(tǒng)計。以下是一個示例:

from collections import Counter

def extract_words(text):
    words = text.split()
    return words

def count_word_frequencies(words):
    word_frequencies = Counter(words)
    return word_frequencies

text = "hello world hello this is a test hello world"

words = extract_words(text)
word_frequencies = count_word_frequencies(words)

print("Words:", words)
print("Word Frequencies:", word_frequencies)

輸出:

Words: ['hello', 'world', 'hello', 'this', 'is', 'a', 'test', 'hello', 'world']
Word Frequencies: Counter({'hello': 3, 'world': 2, 'this': 1, 'is': 1, 'a': 1, 'test': 1})

在這個示例中,我們首先定義了一個名為extract_words的函數(shù),它接受一個字符串參數(shù)text,并使用split()函數(shù)將其拆分為單詞列表。然后,我們定義了一個名為count_word_frequencies的函數(shù),它接受一個單詞列表參數(shù)words,并使用Counter類統(tǒng)計每個單詞出現(xiàn)的次數(shù)。最后,我們使用這兩個函數(shù)提取文本中的單詞并統(tǒng)計它們的詞頻,然后將結(jié)果打印出來。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI