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

时间:2017-03-02 18:29:51

标签: python string list count string-length

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

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

我正在使用一个功能

def char(s):

    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]]

感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:3)

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

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]]

答案 1 :(得分:2)

您有范围问题。您在外部变量len()上调用text而不是每个循环迭代,名为w的变量,因此您获得每个单词的总字符数。

您还有另一个问题,即在外部变量split()上的char函数内调用text而不是传递给函数的对象,您已将其称为s 1}}。

相关问题