簡體   English   中英

如何讓程序按順序打印句子中的單詞數和每個單詞

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

我需要打印用戶指定的句子中有多少個字符,打印用戶指定的句子中有多少個單詞並打印每個單詞,單詞中的字母數以及單詞中的第一個和最后一個字母. 這能做到嗎?

我希望您花點時間了解下面代碼中發生的事情,我建議您閱讀這些資源。

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

請閱讀 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]))

我們不會在堆棧溢出時為您做功課……但我會讓您開始。

您需要的最重要的方法是這兩種方法之一(取決於 python 的版本):

  • Python3.X - input([prompt]) ,.. 如果提示參數存在,則將其寫入標准輸出,而沒有尾隨換行符。 然后該函數從輸入中讀取一行,將其轉換為字符串(去除尾隨的換行符),然后返回該字符串。 讀取 EOF 時,會引發 EOFError。 http://docs.python.org/3/library/functions.html#input
  • Python2.X raw_input([prompt]) ,... 如果提示參數存在,則將其寫入標准輸出,而沒有尾隨換行符。 然后該函數從輸入中讀取一行,將其轉換為字符串(去除尾隨的換行符),然后返回該字符串。 讀取 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([sep[, maxsplit]]) ,...返回字符串中單詞的列表,使用 sep 作為分隔符字符串。 如果給出了 maxsplit,則最多完成 maxsplit 次分割(因此,列表最多有 maxsplit+1 個元素)。 如果未指定 maxsplit 或 -1,則對拆分的數量沒有限制(進行所有可能的拆分)。 http://docs.python.org/2/library/stdtypes.html#str.split

暫無
暫無

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

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