Python
 Computer >> コンピューター >  >> プログラミング >> Python

文字列内の単語の出現をカウントするPythonプログラム


このチュートリアルでは、文字列に単語が出現する回数をカウントするプログラムを作成します。単語と文字列が与えられたら、文字列内の単語の頻度を計算する必要があります。

文字列があるとします私はプログラマーです。私は学生です。 そして、という言葉は 。これから作成するプログラムは、数値 2を返します。 単語が発生する 文字列内で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. 配列内の反転をカウントするPythonプログラム

    この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −リストが表示されます。必要な反転をカウントして表示する必要があります。 反転カウントは、配列をソートするために必要なステップ数をカウントすることによって取得されます。 次に、以下の実装のソリューションを見てみましょう- 例 # count def InvCount(arr, n):    inv_count = 0    for i in range(n):       for j in range(i + 1, n):  

  2. 文字列内の単語の出現をカウントするPythonプログラムを作成しますか?

    ここで、ユーザーは文字列を指定し、ユーザーは出現回数をカウントするための単語も指定しました。私たちの仕事は、発生回数を数えて印刷することです。 例 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