使用Python创建程序:程序必须计算单词数并计算每个单词中的字母数

时间:2016-02-11 03:36:08

标签: python

对我来说困难的部分是信件计数,它需要像这样。 例:糖果是红色的(输出需要: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

3 个答案:

答案 0 :(得分:2)

试试这个:

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]
>>> 

答案 1 :(得分:1)

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()
当用户输入'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()

答案 2 :(得分:0)

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