Python で文字列内の各単語の長さを統計する

Document 对象参考手册Python3 の例

文字列内の各単語の長さを統計する 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)

コードの解説:

  1. word_lengths(s)関数は文字列をs引数として受け取ります。
  2. s.split()文字列をsスペースで分割して単語リストにします。words。
  3. [len(word) for word in words]リスト内包表記を使用してwordsリスト内の各単語を走査し、その長さを計算して、すべての単語の長さを含むリストを生成します。lengths。
  4. dict(zip(words, lengths)) 将 wordsとlengths2つのリストを1つの辞書に組み合わせます。キーは単語、値は対応する長さです。
  5. 最後に、関数はこの辞書を返します。

出力結果:

例

{'Hello': 5, 'world': 5, 'this': 4, 'is': 2, 'a': 1, 'test': 4}

Document 对象参考手册Python3 の例

その他の拡張