簡體   English   中英

使用Python創建程序:程序必須計算單詞數並計算每個單詞中的字母數

[英]Create a Program using Python: Program must count the number of words and count the number of letters in each word

對我來說,最困難的部分是字母計數,它需要像這樣。 例如:糖果是紅色的(輸出必須是:3 5 2 3)。 此外,當前代碼還考慮了空格,不應考慮空格。

這是我到目前為止的內容:

def main():
    phrase = input("Enter Your Sentence:")
    words = phrase.split()
    WordCount = len(words)
    LetterCount = len(phrase)
    print("Total Amount of Words in Sentence: %s" % WordCount)
    print("Total Amount of Letters in Sentence: %s" % LetterCount)
main()

例:

Enter your sentence: The sky is blue  
Total amount of words: 4 
Total amount of letters: 3 3 2 4

嘗試這個:

def main():
    phrase = input("Enter Your Sentence: ")
    return [len(item) for item in phrase.split()]

>>> main()
Enter Your Sentence: The candy is red
[3, 5, 2, 3]
>>> main()
Enter Your Sentence: These are words
[5, 3, 5]
>>> 
def main():
        phrase = input("Enter Your Sentence:")
        words = phrase.split()
        WordCount = len(words)
        LetterCount = [len(word) for word in words]
        print("Total Amount of Words in Sentence:", WordCount)
        print("Total Amount of Letters in Sentence:", LetterCount)

main()

使用無限的while循環,並在用戶輸入“ quit”時退出循環

def main():
    while True:
        phrase = input("Enter Your Sentence or quit to exit: \n")
        if phrase.lower() == 'quit':
            break
        else:
            words = phrase.split()
            WordCount = len(words)
            LetterCount = [len(word) for word in words]
            print("Total Amount of Words in Sentence:", WordCount)
            print("Total Amount of Letters in Sentence:", LetterCount)

main()
def user_input():
    phrase = input("Enter your sentence: ")
    return phrase

def word_count(phrase):
    list_of_words = phrase.split()
    count = 0
    for word in list_of_words:
        count += 1
    return count

def letter_count(phrase):
    list_of_words = phrase.split()
    count = 0
    letter_list = []
    for word in list_of_words:
        for char in word:
            count += 1
        letter_list += [count]
        count = 0
    letter_string = ' '.join(map(str, letter_list))
    return letter_string

def restart_program():
    restart_question = "Would you like to restart the program (y or n)? "
    restart_answer = str(input(restart_question.lower()))
    return restart_answer

def main():
    start_again = "y"
    while start_again == "y":
        phrase = user_input()
        number_words = word_count(phrase)
        letters = letter_count(phrase)

        print ("Total amount of words: ", number_words)
        print ("Total amount of letters: ", letters)
        print ()

        start_again = restart_program()

        print ()

    print ("Good Bye")

main()

示例輸出:

Enter your sentence: The sky is blue
Total amount of words:  4
Total amount of letters:  3 3 2 4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM