Linux 拨号vps windows公众号手机端

python怎么统计单词个数

lewis 8年前 (2017-02-11) 阅读数 9 #程序编程
文章标签 python

可以通过以下步骤来统计单词的个数:

  1. 将文本内容分割成单词列表
  2. 遍历单词列表,统计每个单词的出现次数

下面是一个示例代码,用于统计文本中单词的个数:

def count_words(text):
    # 将文本内容转换为小写,并去除标点符号
    text = text.lower()
    text = ''.join(e for e in text if e.isalnum() or e.isspace())
    
    # 分割文本内容为单词列表
    words = text.split()
    
    # 统计每个单词的出现次数
    word_count = {}
    for word in words:
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1
    
    return word_count

text = "Python is a popular programming language. Python is used in various fields including web development, data science, and machine learning."
result = count_words(text)
print(result)

运行以上代码,将输出每个单词及其出现的次数。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门