【问题标题】:python programs to count letters in each word of a sentencepython程序计算句子中每个单词中的字母
【发布时间】:2016-05-18 13:18:36
【问题描述】:

我对 python 还是很陌生,我需要一个程序,它不仅可以计算输入句子中的单词,还可以计算每个单词中的字母数。这就是我到目前为止所拥有的。任何帮助将不胜感激!

def main():
    s = input("Please enter your sentence: ")
    words = s.split()
    wordCount = len(words)
    print ("Your word and letter counts are:", wordCount)
main()

【问题讨论】:

  • 单句输入是否需要 TotalWordCount 和 TotalLetterCount?
  • 两者。我使用 for 循环来获取计数。 s = input("请输入你的句子:") words = s.split() wordCount = len(words) print("你的单词和字母数是:", wordCount) count = 0 for ch in words: count += 1 print(len(ch)) main()

标签: python


【解决方案1】:

您可以生成从单词到单词长度的映射,如下所示:

s = "this is a sentence"
words = s.split()
letter_count_per_word = {w:len(w) for w in words}

这会产生

letter_count_per_word == {'this': 4, 'a': 1, 'is': 2, 'sentence': 8}

【讨论】:

  • 如果你不想被单词所困扰,你可以通过letter_count_per_word = [len(w) for w in words]获取字母数。
  • 感谢您的信息!我以前没见过这种方法。我完成了代码,但现在我不确定如何格式化输出。我希望每个单词的字符数出现在同一行。你知道我该怎么做吗?打印功能中的“格式”?
  • 您希望输出看起来像什么?
【解决方案2】:

实际上,Python 有一个名为 Counter 的集合类,它会为您计算每个单词出现的次数。

from collections import Counter

my_sentence = 'Python is a widely used programming language'
print Counter(my_sentence.split())

输出

Counter({'a': 1, 'used': 1, 'language': 1, 'Python': 1, 'is': 1, 'programming': 1, 'widely': 1})

【讨论】:

    【解决方案3】:

    试试下面的代码

    words = str(input("Please enter your sentence. "))
    
    print (len(words))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-15
      • 2016-07-06
      • 2020-11-16
      • 2015-08-18
      • 2021-04-01
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      相关资源
      最近更新 更多