Python 程序来统计给定字符串中的单词数?
假设我们有一个“字符串”和一个“单词”,我们需要使用 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
以上是其他两种查找用户输入字符串中的单词数的办法。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP