温馨提示×

python怎么统计单词个数

小亿
990
2024-02-19 09:57:22
栏目: 编程语言

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

  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) 

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

0