Python で文字列内の各単語の長さを統計する
文字列内の各単語の長さを統計する Python プログラムを作成します。このプログラムは、まず文字列を単語リストに分割し、次に各単語を走査してその長さを計算します。
例
def word_lengths(s):
words = s.split()
lengths = [len(word) for word in words]
return dict(zip(words, lengths))
# サンプル文字列
text = "Hello world this is a test"
result = word_lengths(text)
print(result)
words = s.split()
lengths = [len(word) for word in words]
return dict(zip(words, lengths))
# サンプル文字列
text = "Hello world this is a test"
result = word_lengths(text)
print(result)
コードの解説:
word_lengths(s)関数は文字列をs引数として受け取ります。s.split()文字列をsスペースで分割して単語リストにします。words。[len(word) for word in words]リスト内包表記を使用してwordsリスト内の各単語を走査し、その長さを計算して、すべての単語の長さを含むリストを生成します。lengths。dict(zip(words, lengths))将wordsとlengths2つのリストを1つの辞書に組み合わせます。キーは単語、値は対応する長さです。- 最後に、関数はこの辞書を返します。
出力結果:
例
{'Hello': 5, 'world': 5, 'this': 4, 'is': 2, 'a': 1, 'test': 4}
Python3 の例