You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Python函数count_words统计3段文本的单词数量

Python 文本单词数统计实现

待统计文本定义

text1 = "He is tall, fat and ugly."
text2 = "He is a very fearful and crying boy, but intelligent."
text3 = "She has a pretty face, but she's not very smart."

补全单词计数函数

通过拆分文本、清洗末尾标点的逻辑实现计数,补全后的代码如下:

def count_words(text):
    num_words = 0
    # 按空格拆分文本得到单词片段
    word_segments = text.split()
    for seg in word_segments:
        # 去除片段末尾的逗号、句号等非单词字符
        clean_word = seg.rstrip('.,!?')
        if clean_word:
            num_words += 1
    return num_words

调用函数输出结果

直接使用给定的调用逻辑即可:

num_words = count_words(text1)
print("Text 1")
print("The word number is %d" % num_words)

num_words = count_words(text2)
print("Text 2")
print("The word number is %d" % num_words)

num_words = count_words(text3)
print("Text 3")
print("The word number is %d" % num_words)

最终统计结果

  • Text 1 单词数:6
  • Text 2 单词数:10
  • Text 3 单词数:10

内容的提问来源于stack exchange,提问作者Angellys Correa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 00:45:04