您好,登錄后才能下訂單哦!
在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é)果打印出來。
免責(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)容。