如何让程序打印句子的单词数量及每个单词的顺序

-4 投票
3 回答
3461 浏览
提问于 2025-04-18 00:23

我需要计算用户指定的句子中有多少个字符,计算句子中有多少个单词,并且打印出每个单词、每个单词的字母数量,以及每个单词的第一个字母和最后一个字母。这可以做到吗?

3 个回答

1

我们在Stack Overflow上不会帮你做作业……但我可以帮你入门。

你最需要的方法是以下两种之一(取决于你用的Python版本):

  • Python3.X - input([提示]),如果有提示参数,它会在输出中显示,但不会换行。这个函数会从输入中读取一行,把它转换成字符串(去掉末尾的换行符),然后返回这个字符串。当读取到文件结束符(EOF)时,会抛出EOFError错误。http://docs.python.org/3/library/functions.html#input
  • Python2.X - raw_input([提示]),用法和Python3.X的input类似。如果有提示参数,它会在输出中显示,但不会换行。这个函数同样会从输入中读取一行,转换成字符串(去掉末尾的换行符),然后返回。当读取到文件结束符(EOF)时,也会抛出EOFError错误。http://docs.python.org/2.7/library/functions.html#raw_input

你可以这样使用它:

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

如你所见,写入的文本被存储在my_sentance变量中。

要获取字符串中的字符数量,你需要明白字符串其实就是一个列表!所以如果你想知道字符的数量,可以使用:

我就不告诉你怎么用这个了,你自己去研究吧。

最后,你还需要使用一个字符串的内置函数:

  • str.split([分隔符[, 最大分割数]]),这个函数会返回字符串中单词的列表,使用分隔符作为分隔符。如果给定了最大分割数,最多只会进行maxsplit次分割(因此,列表最多会有maxsplit+1个元素)。如果没有指定最大分割数或指定为-1,则分割次数没有限制(会进行所有可能的分割)。http://docs.python.org/2/library/stdtypes.html#str.split
1

请查看一下Python的字符串文档,里面的内容很清楚。这里简单解释一下不同部分,并加上一些注释。

我们知道,一个句子是由单词组成的,而每个单词又是由字母组成的。我们首先要做的就是把句子用split方法分割成单词。这个列表中的每一项都是一个单词,而每个单词则是由一串字符组成的,我们可以获取其中的每一个字符。

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

我希望你能花点时间理解下面代码的内容,并建议你阅读这些资源。

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

撰写回答