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

Output a list from a sentence and count characters for each word

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

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

我正在使用函数

def 字符:

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

感谢任何帮助,谢谢。

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

你有另一个问题,你在你的 char 函数中调用 split() 外部变量 text 而不是传递给函数的对象,你称之为 s.

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

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