我对python很陌生,我需要一个程序,它不仅可以计算输入句子中的单词,还可以计算每个单词中的字母数。这就是我到目前为止所拥有的。非常感谢任何帮助!
def main():
s = input("Please enter your sentence: ")
words = s.split()
wordCount = len(words)
print ("Your word and letter counts are:", wordCount)
main()
答案 0 :(得分:5)
您可以生成从单词到单词长度的映射,如下所示:
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}
答案 1 :(得分:1)
实际上,Python有一个名为Counter的集合类,它会为你计算每个单词的出现次数。
from collections import Counter
my_sentence = 'Python is a widely used programming language'
print Counter(my_sentence.split())
计数器({'a':1,'使用':1,'语言':1,'Python':1,'是':1,'编程':1,'广泛':1})< / p>
答案 2 :(得分:-1)
尝试以下代码
words = str(input("Please enter your sentence. "))
print (len(words)