Pythonで文字列内の単語数を数える

Document 对象参考手册Python3 実例

Pythonでは、文字列を単語のリストに分割し、そのリストの長さを計算することで、文字列内の単語数を取得できます。以下は簡単なサンプルコードです。

実例

def count_words(text):
    words = text.split()
    return len(words)

# サンプル文字列
text = "Hello world, this is a test."
word_count = count_words(text)
print(f"The number of words in the text is: {word_count}")

コード解析:

  1. count_words関数は文字列を受け取りtextパラメータとして。
  2. text.split()文字列をスペースで分割して単語のリストにします。デフォルトでは、split()このメソッドは、任意の空白文字(スペース、改行など)を区切り文字として扱います。
  3. len(words)単語リストの長さ、つまり単語の数を返します。
  4. サンプル文字列text6つの単語が含まれています。
  5. print関数は単語の数を出力します。

出力結果:

The number of words in the text is: 6

Document 对象参考手册Python3 実例

その他の拡張