【问题标题】:Python find all the words with less than 5 letters in the string in a given textPython 查找给定文本中字符串中所有字母少于 5 个的单词
【发布时间】:2022-11-16 13:05:37
【问题描述】:

此代码现在不起作用,因为我不知道我应该使用的确切代码。我需要打印出包含少于 5 个字母的单词数。 这就是我一直在尝试的:

text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout."
words = text.split()
letterCount = {w: len(w) for w in words}

lessthan5 = '1,2,3,4'
count = 0
if words == lessthan5 :      #i put words to refer to line 3(letter count)
     result = count + 1
     print(result)

我需要的输出是一个整数,ex.17。 请帮助非常感谢你

【问题讨论】:

  • sum([1 for i in text.split() if len(i)<5])
  • 你真的不需要ifclause;你可以对布尔值求和:sum(len(word) < 5 for word in words)

标签: python list


【解决方案1】:

希望这有助于:

text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout."
words = text.split()
count = 0
for word in words:
    if len(word) < 5:
        count = count + 1

print(count)

【讨论】:

  • 太感谢了。
  • @Ruby 欢迎,不要忘记投票和/或接受作为答案。
猜你喜欢
  • 2019-05-12
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多