Pythonで文字列内の単語数を数える
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}")
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}")
コード解析:
count_words関数は文字列を受け取りtextパラメータとして。text.split()文字列をスペースで分割して単語のリストにします。デフォルトでは、split()このメソッドは、任意の空白文字(スペース、改行など)を区切り文字として扱います。len(words)単語リストの長さ、つまり単語の数を返します。- サンプル文字列
text6つの単語が含まれています。 print関数は単語の数を出力します。
出力結果:
The number of words in the text is: 6その他の拡張
Python3 実例