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))wordslengths 两个列表组合成一个字典,其中键是单词,值是对应的长度。
  5. 最后,函数返回这个字典。

输出结果:

实例

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

Document 对象参考手册 Python3 实例