如何获取句子中单词的长度?

10 投票
4 回答
52865 浏览
提问于 2025-04-18 00:35

我想要获取一句话中每个单词的长度。我知道可以用“len”这个函数,但我不知道怎么才能得到每个单词的长度。

我不想要这样的结果

>>> s = "python is pretty fun to use"
>>> len(s)
27
>>>

我想要这样的结果

6, 2, 6, 3, 2, 3

也就是每个单词的实际长度。

4 个回答

0

iCodez说得对,不过需要对脚本形式做一些小调整。

s = 'python is pretty fun to use'
li = list(map(len, s.split()))

然后在命令行或者打印语句中输入:

print(li)
7

使用这个:

s = "python is pretty fun to use"
[len(x) for x in s.split()]

示例输出:

>>> [len(x) for x in s.split()]
[6, 2, 6, 3, 2, 3]

后台发生了什么?

s.split() 这个方法会在字符串中的空格处进行切分,然后把句子里的每个单词放到一个列表里:

>>> s.split()
['python', 'is', 'pretty', 'fun', 'to', 'use']

接着,我们用len()来计算每个单词的长度。然后把每个长度都放到一个列表里,这样最后就能方便地返回结果。

这一切都在这个列表推导式中完成:

[len(x) for x in s.split()]

还是有点困惑?这实际上是同样的概念,只是更详细地分解了一下:

results = []
for x in s.split():
    word_length = len(x)
    results.append(word_length)
print results 

如果你想把它们单独打印出来,就像你问题里提到的那样,可以使用:

for x in [len(x) for x in s.split()]: 
    print x
8

使用 map1str.split

>>> s = "python is pretty fun to use"
>>> map(len, s.split())
[6, 2, 6, 3, 2, 3]
>>>

1注意:在 Python 3 中,map 返回的是一个迭代器。如果你使用的是这个版本,可能需要把它放进 list 里,这样才能得到像 Python 2 中 map 返回的那样的整数列表:

>>> # Python 3 interpreter
>>> s = "python is pretty fun to use"
>>> map(len, s.split())
<map object at 0x02364ED0>
>>> list(map(len, s.split()))
[6, 2, 6, 3, 2, 3]
>>>
16

试试这个,使用 map() 函数来对句子里的每个单词应用 len() 函数,记住 split() 可以把句子分成一个个单词,形成一个列表:

s = "python is pretty fun to use"
map(len, s.split())       # assuming Python 2.x
list(map(len, s.split())) # assuming Python 3.x

或者,你也可以用 列表推导式 来达到同样的效果:

[len(x) for x in s.split()]

无论哪种方法,结果都是一个列表,里面包含了句子中每个单词的长度:

[6, 2, 6, 3, 2, 3]

撰写回答