Skip to main content
 首页 » 编程设计

python之从句子中输出一个列表并计算每个单词的字符数

2025年05月04日24xing901022

我需要在 2 元素列表中输出一个包含字符数的列表,该列表给出了每个单词的字符数:

[['How', 3], ['are', 3], ['you', 3], ['today', 5]] 

我正在使用一个函数

定义字符:

    l = []  # list for holding your result 
 
    # convert string s into a list of 2-element-lists 
    s = text.split() 
    s = [[word ,len(word)] for word in s.split()] 
    print("Output:\n", s) 
    print() 
    return l 
 
 
text = "How are you today" 
l = char(text) 
print() 

但我得到的输出是计算每个单词的总字符数,而不是每个单词的特定字符数:

[['How', 17], ['are', 17], ['you', 17], ['today', 17]] 

感谢任何帮助,谢谢。

请您参考如下方法:

你的问题是你在计算文本中的字符数,但你必须计算每个单词中的字符数。最后,您甚至可以将代码简化为:

def char(s): 
    return [[word ,len(word)] for word in s.split()] 

然后你可以通过以下方式调用它:

text = "How are you today" 
l = char(text) 
print(l) 

输出:

[['How', 3], ['are', 3], ['you', 3], ['today', 5]]