简体   繁体   中英

How do I get a program to print the number of words in a sentence and each word in order

I need to print how many characters there are in a sentence the user specifies, print how many words there are in a sentence the user specifies and print each word, the number of letters in the word, and the first and last letter in the word. Can this be done?

I want you to take your time and understand what is going on in the code below and I suggest you to read these resources.

http://docs.python.org/3/library/re.html

http://docs.python.org/3/library/functions.html#len

http://docs.python.org/3/library/functions.html

http://docs.python.org/3/library/stdtypes.html#str.split

import re


def count_letter(word):
    """(str) -> int

    Return the number of letters in a word.

    >>> count_letter('cat')
    3
    >>> count_letter('cat1')
    3

    """
    return len(re.findall('[a-zA-Z]', word))


if __name__ == '__main__':
    sentence = input('Please enter your sentence: ')
    words = re.sub("[^\w]", " ",  sentence).split()

    # The number of characters in the sentence.
    print(len(sentence))
    # The number of words in the sentence.
    print(len(words))
    # Print all the words in the sentence, the number of letters, the first
    # and last letter.
    for i in words:
        print(i, count_letter(i), i[0], i[-1])

Please enter your sentence: hello user
10
2
hello 5 h o
user 4 u r

Please read Python's string documentation, it is self explanatory. Here is a short explanation of the different parts with some comments.

We know that a sentence is composed of words, each of which is composed of letters. What we have to do first is to split the sentence into words. Each entry in this list is a word, and each word is stored in a form of a succession of characters and we can get each of them.

sentence = "This is my sentence"

# split the sentence
words = sentence.split()
# use len() to obtain the number of elements (words) in the list words
print('There are {} words in the given sentence'.format(len(words)))
# go through each word
for word in words:
    # len() counts the number of elements again,
    # but this time it's the chars in the string 
    print('There are {} characters in the word "{}"'.format(len(word), word))

    # python is a 0-based language, in the sense that the first element is indexed at 0
    # you can go backward in an array too using negative indices.
    #
    # However, notice that the last element is at -1 and second to last is -2,
    # it can be a little bit confusing at the beginning when we know that the second
    # element from the start is indexed at 1 and not 2.
    print('The first being "{}" and the last "{}"'.format(word[0], word[-1]))

We don't do your homework for you on stack overflow... but I will get you started.

The most important method you will need is one of these two (depending on the version of python):

  • Python3.X - input([prompt]) ,.. If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. http://docs.python.org/3/library/functions.html#input
  • Python2.X raw_input([prompt]) ,... If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. http://docs.python.org/2.7/library/functions.html#raw_input

You can use them like

>>> my_sentance = raw_input("Do you want us to do your homework?\n")
Do you want us to do your homework?
yes
>>> my_sentance
'yes'

as you can see, the text wrote was stroed in the my_sentance variable

To get the amount of characters in a string, you need to understand that a string is really just a list! So if you want to know the amount of characters you can use:

I'll let you figure out how to use it.

Finally you're going to need to use a built in function for a string:

  • str.split([sep[, maxsplit]]) ,...Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made). http://docs.python.org/2/library/stdtypes.html#str.split

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM