编写一个 Python 程序,通过实际示例计算字符串中的总单词数。
Python 程序:计算字符串中的单词数示例
此 Python 程序允许用户输入一个字符串(或字符数组)。接下来,它使用 For 循环计算此字符串中存在的总单词数。在这里,我们使用 Python For 循环迭代字符串中的每个字符。在 For 循环内部,我们使用 If 语句检查是否存在空格。如果找到空格,则总单词计数会增加。
str1 = input("Please Enter your Own String : ")
total = 1
for i in range(len(str1)):
if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
total = total + 1
print("Total Number of Words in this String = ", total)

Python 程序:计算字符串中的单词数示例 2
这个 Total Number of Words in a String 的 Python 程序与上面相同。但是,我们只是将 For 循环替换为 While 循环。
str1 = input("Please Enter your Own String : ")
total = 1
i = 0
while(i < len(str1)):
if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
total = total + 1
i = i + 1
print("Total Number of Words in this String = ", total)
使用 while 循环输出计算字符串中的单词数
Please Enter your Own String : Tutorial Gateway
Total Number of Words in this String = 2
Python 程序:计算字符串中的总单词数示例 3
这个 Count Total Number of Words in a String 与第一个示例相同。但是,这次我们使用了 函数概念来分离 Python 逻辑。
def Count_Total_Words(str1):
total = 1
for i in range(len(str1)):
if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
total = total + 1
return total
string = input("Please Enter your Own String : ")
leng = Count_Total_Words(string)
print("Total Number of Words in this String = ", leng)
使用函数输出计算字符串中的总单词数
Please Enter your Own String : Python Hello World Program
Total Number of Words in this String = 4