python程序计算句子中每个单词的字母数

python程序计算句子中每个单词的字母数,python,Python,我对python非常陌生,我需要一个程序,它不仅可以计算输入句子中的单词,还可以计算每个单词中的字母数。这就是我目前所拥有的。任何帮助都将不胜感激 def main(): s = input("Please enter your sentence: ") words = s.split() wordCount = len(words) print ("Your word and letter counts are:", wordCount) main() 您可以

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

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

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

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}

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

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}

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

from collections import Counter

my_sentence = 'Python is a widely used programming language'
print Counter(my_sentence.split())
输出
计数器({'a':1',used':1,'language':1,'Python':1,'is':1,'programming':1,'s':1})

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

from collections import Counter

my_sentence = 'Python is a widely used programming language'
print Counter(my_sentence.split())
输出 计数器({'a':1',used':1,'language':1,'Python':1,'is':1,'programming':1,'s':1})

尝试以下代码

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

print (len(words))
尝试以下代码

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

print (len(words))

您是否希望一个句子输入的TotalWordCount和totaletterCount?两者都是。我使用for循环来获得计数。s=input(“请输入您的句子:”)words=s.split()wordCount=len(words)print(“您的单词和字母计数为:”,wordCount)count=0,对于ch in words:count+=1 print(len(ch))main()您是否希望单个句子输入有TotalWordCount和totalettercount?两者都有。我使用for循环来获得计数。s=input(“请输入您的句子:”)words=s.split()wordCount=len(words)print(“您的单词和字母计数为:”,wordCount)count=0,对于ch in words:count+=1 print(len(ch))main(),如果您不想为这些单词的内容而烦恼,您可以通过
letter\u count\u per\u word=[len(w)for w in words]
获得字母计数。感谢您提供的信息!我以前从未见过这种方法。我完成了代码,但现在我不确定如何格式化输出。我希望每个单词的字符数出现在同一行上。你知道我怎么做吗?”打印函数中的“格式化”?您希望输出的确切形式是什么?如果您不想为单词的内容而烦恼,您可以通过
字母计数/u单词=[len(w)for w in words]
获得字母计数。感谢您提供的信息!我以前从未见过这种方法。我完成了代码,但现在我不确定如何格式化输出。我希望每个单词的字符数出现在同一行上。你知道我怎么做吗?”打印函数中的“format”(格式化)?您希望输出看起来像什么?