[英]python programs to count letters in each word of a sentence
我對 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}
實際上,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})
試試下面的代碼
words = str(input("Please enter your sentence. "))
print (len(words))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.