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
結論
如果您對程式有任何疑問,請在評論區提出。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP