【问题标题】:Output a list from a sentence and count characters for each word从句子中输出列表并计算每个单词的字符数
【发布时间】:2017-07-22 15:15:54
【问题描述】:

我需要在 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]]

感谢您的帮助,谢谢。

【问题讨论】:

  • 使用 len(w) 代替 len(text)
  • 因为 len(text) 是完整字​​符串的长度
  • @Supernova,考虑使用您传递给函数的参数s,而不是使用全局变量text
  • 我试过它为每个单词输出 4,因为它计算字符串中的单词数
  • s = text.split() s = ([ [word,len(s)] for word in s ]) print("Output:\n", s) print() return l

标签: python string list count string-length


【解决方案1】:

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

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

【讨论】:

  • @Imiguelvargasf 它的说法没有属性分裂
  • @Imiguelvargasf 我已经更新了上面的代码,但仍然在拆分时生成属性错误
  • @Supernova,我刚刚检查了代码,它的工作就像一个魅力。您是否将字符串传递给函数?像这样:text = "How are you today"; l = char(text)
  • @Supernova,我刚刚更新了我的答案,这绝对有效
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2022-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多