我是 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}
