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
上面也有其他几种方法,可以找到用户输入的字符串中的单词数。
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短