Python实现统计词量
题目统计词量要求请用程序实现输入一段仅由英文字母、空格组成的文本,统计这段文本中的单词数量,并将统计结果输出。输入格式在 1 行中输入一段英文文本输出格式统计单词数量,并在 1 行上输出结果示例 1输入i love python输出3示例 2输入hello this is lee who are you输出7代码:str = input("请您输入一...
·
题目
统计词量
要求
请用程序实现
输入一段仅由英文字母、空格组成的文本,统计这段文本中的单词数量,并将统计结果输出。
输入格式
在 1 行中输入一段英文文本
输出格式
统计单词数量,并在 1 行上输出结果
示例 1
输入
i love python
输出
3
示例 2
输入
hello this is lee who are you
输出
7
代码:
str = input("请您输入一串字符串:")
str1 = str.strip() #去掉头尾空格
index = 0
count = 0
while index < len(str1):
while str1[index] != " ": #有空格时结束当前循环
index += 1
if index == len(str1): #下标与字符串长度相等结束当前循环
break
count += 1 #计算单词的个数
if index == len(str1): #下标与字符串长度相等结束当前循环
break
while str1[index] == " ": #单词之间多个空格时,下标加1
index += 1
print(count)
更多推荐
已为社区贡献1条内容
所有评论(0)