Python 程序如何计算给定字符串中的单词数?
pythonserver side programmingprogramming更新于 2025/8/12 23:08:17
假设我们有一个"字符串"和"单词",我们需要使用 Python 找出该单词在字符串中的出现次数。这就是我们在本部分要做的,计算给定字符串中的单词数并打印出来。
计算给定字符串中的单词数
方法 1:使用 for 循环
#方法 1:使用 for 循环
test_stirng = input("String to search is : ")
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)
结果
String to search is : 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("String to search is : ")
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)
结果
String to search is : 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("String to search is :")
total = Count_words(test_string)
print("Total Number of Words in our input string is: ", total)
结果
String to search is :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
以上还有其他几种方法,可以查找用户输入的字符串中的单词数。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

