簡體   English   中英

Python:具有錯誤檢查的句子中的平均單詞長度

[英]Python: Average word length in a sentence with error checking

我必須創建一個程序來計算句子的平均單詞長度。 它還必須提示用戶輸入句子,直到輸入句點為止,使用不返回任何值的功能來向用戶提供指示,並檢查是否沒有單詞。

到目前為止,這就是我所擁有的:

def main():
    print('This program calculates the average word length in a sentence!')
    s = input('Please enter a sentence: ')
    words = s.split()
    wordCount = len(words)
    sum = 0

    for w in words:
        ch = len(w)
        sum = sum + ch
        avg = float(sum)/float(wordCount)

    while True:
        x = input('Enter a period to stop:')
        if x == '.':
            break

    print('the average word length is ', avg)
main()

我一直在網上在線拼湊此問題的其他答案,試圖找到一種方法來實現這一目標。 請幫忙。 :(我只是一個初學者,如果這看起來很瑣碎,我感到抱歉。但是我想找出我做錯了什么。

編輯:

要求我使用while True循環,並且必須輸入每個句子的平均單詞長度。 要退出程序,必須輸入一個句點。 如果沒有字數統計,我需要有一種方法來檢查錯誤。 如果沒有值可以返回,我需要它循環回到開頭。

您是否只需要在末尾除以wordCount

average = sum / wordCount
print('the average word length is ', average) 

我看不到涉及x和句點的while True循環的用法,但我相信您想輸出float(sum)/float(wordCount) 現在,您只是輸出所有長度的總和。

我建議您重新組織程序。 編寫一個函數,要求用戶提供句子,計算字數並打印平均值。 然后,創建另一個設置while True:函數while True: loop; 在循環中,詢問用戶是否繼續。

這將使您“關注點分離”:詢問用戶句子的代碼將在一起,而反復詢問的代碼則與之分開。

您可以組織得更多:創建一個函數來計算句子的平均單詞長度,然后從用戶輸入函數中調用該函數。

PS:不要忘記處理句子中有0個單詞的情況。 如果用戶輸入長度為零的句子,建議您將平均單詞長度設為0。

if wordCount != 0:
    avg = float(sum) / float(wordCount)
else:
    avg = 0

暫無
暫無

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

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