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
结论
如果您对该程序有任何疑问,请在评论部分中询问。
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿