Python程序来计数给定字符串中的单词?

假设我们有一个“字符串”和“单词”,我们需要使用python查找该单词在字符串中的出现次数。这就是我们在本节中要执行的操作,计算给定字符串中的单词数并打印出来。

计算给定字符串中的单词数

方法1:使用for循环

#方法1:使用for循环

test_stirng = input("要搜索的字符串是: ")
total = 1

for i in range(len(test_stirng)):
   if(test_stirng[i] == ' ' or test_stirng == '\n' or test_stirng == '\t'):
      total = total + 1

print("Total Number of Words in our input string is: ", total)

结果

要搜索的字符串是: Python is a high level language. Python is interpreted language. Python is general-purpose programming language
Total Number of Words in our input string is: 16

#方法2:使用while循环

test_stirng = input("要搜索的字符串是: ")
total = 1
i = 0
while(i < len(test_stirng)):
   if(test_stirng[i] == ' ' or test_stirng == '\n' or test_stirng == '\t'):
      total = total + 1
   i +=1

print("Total Number of Words in our input string is: ", total)

结果

要搜索的字符串是: Python is a high level language. Python is interpreted language. Python is general-purpose programming language
Total Number of Words in our input string is: 16

#方法3:使用功能

def Count_words(test_string):
   word_count = 1
   for i in range(len(test_string)):
      if(test_string[i] == ' ' or test_string == '\n' or test_string == '\t'):
         word_count += 1
   return word_count
test_string = input("要搜索的字符串是:")
total = Count_words(test_string)
print("Total Number of Words in our input string is: ", total)

结果

要搜索的字符串是:Python is a high level language. Python is interpreted language. Python is general-purpose programming language
Total Number of Words in our input string is: 16

上面也有其他几种方法,可以找到用户输入的字符串中的单词数。