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)
输出结果
如果运行上面的程序,您将得到以下结果。
2
结论
如果您对该程序有任何疑问,请在评论部分中询问。