编写一个python程序来计算字符串中单词的出现次数?
在此,用户给定了字符串,用户也给了单词以计算出现次数。我们的任务是计算出现次数并打印出来。
示例
Input: Python is an interpreted high-level programming language for general purpose programming. Enter the word to count occurrence ::>programming Output:: 2
算法
wordoccurences(n,p) /* n is input string and p is the word to count occurrence */ Step 1: split the string by space Step 2: we use one counter variable c and it’s initialized by 0 and if word is match then c is incremented by 1. Step 3: then we searching using for loop. Step 4: if condition is true then counter c is increased and display the final result.
范例程式码
def wordoccurences(n, p):
x = n.split(" ")
c = 0
for i in range(0, len(x)):
# if match found increase count
if (p == x[i]):
c = c + 1
return c
# Driver code
n=input("Enter String ::>")
p=input("Enter the word to count occurrence ::>")
print("THE NUMBER OF OCCURRENCE OF A WORD ",p,"is",wordoccurences(n, p))
# To count the number of occurrence of a word in the given string输出结果
Enter String ::>python is an interpreted high level programming language for general purpose programming Enter the word to count occurrence ::>programming THE NUMBER OF OCCURRENCE OF A WORD programming is 2
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短