Python程序统计字符串中单词出现的次数
在本教程中,我们将编写一个程序来计算一个单词在一个字符串中出现的次数。给定一个单词和一个字符串,我们需要计算该单词在字符串中的频率。
假设我们有一个字符串 **我是一个程序员。我是一个学生。** 和单词 **是**。我们将要编写的程序将返回数字 **2**,因为该单词在字符串中出现了两次。
让我们按照以下步骤来实现我们的目标。
算法
1. Initialize the string and the word as two variables. 2. Split the string at spaces using the split() method. We will get a list of words. 3. Initialize a variable count to zero. 4. Iterate over the list. 4.1. Check whether the word in the list is equal to the given the word or not. 4.1.1. Increment the count if the two words are matched. 5. Print the count.
先尝试自己编写程序代码。让我们看看代码。
示例
## initializing the string and the word string = "I am programmer. I am student." word = "am" ## splitting the string at space words = string.split() ## initializing count variable to 0 count = 0 ## iterating over the list for w in words: ## checking the match of the words if w == word: ## incrementint count on match count += 1 ## printing the count print(count)
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
运行上述程序后,您将获得以下结果。
2
结论
如果您对程序有任何疑问,请在评论区提出。
广告