温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

字符串中单词的提取与词频统计

发布时间:2024-10-01 10:06:34 来源:亿速云 阅读:81 作者:小樊 栏目:编程语言

在Python中,我们可以使用split()函数来提取字符串中的单词,并使用collections模块中的Counter类来进行词频统计。以下是一个示例:

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的函数,它接受一个字符串参数text,并使用split()函数将其拆分为单词列表。然后,我们定义了一个名为count_word_frequencies的函数,它接受一个单词列表参数words,并使用Counter类统计每个单词出现的次数。最后,我们使用这两个函数提取文本中的单词并统计它们的词频,然后将结果打印出来。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI