欢迎访问宙启技术站
智能推送

实现一个Python程序来计算字符串中单词的个数

发布时间:2023-12-04 12:50:05

这里是一个实现计算字符串中单词个数的Python程序:

def count_words(string):
    words = string.split() # 使用split()方法将字符串分割为单词列表
    return len(words) # 返回单词列表的长度即单词个数

# 使用例子
input_string = "Hello, how are you?"
word_count = count_words(input_string)
print("Input string:", input_string)
print("Word count:", word_count)

运行上述代码,输出结果如下:

Input string: Hello, how are you?
Word count: 4

这个程序中,count_words()函数接受一个字符串作为参数。它使用字符串的split()方法将字符串分割为单词,并返回单词列表的长度,即单词的个数。在使用例子中,我们将字符串"Hello, how are you?"作为输入,程序将输出该字符串中的单词个数:4。