亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何創建不包含空格的字數統計?

如何創建不包含空格的字數統計?

jeck貓 2023-10-11 10:00:06
我是 python 的初學者,我的任務是創建一個函數,該函數接受字符串作為參數并返回字符串中的單詞數。我在分配空格和空白字符串時遇到問題。我覺得我錯過了一些東西,但又對錯過了什么或搞砸了什么感到有點迷失。我們也不能使用 split。任何指導或幫助將不勝感激這是我到目前為止所擁有的:def word_count(str):count = 1for i in str:    if (i == ' '):       count += 1                    print (count)        word_count('hello') --> 輸出 = 1 (到目前為止正確)word_count('你好嗎?') --> 輸出 = 3 (也是正確的/至少是我正在尋找的)word_count('這個字符串有寬空格') --> 輸出 = 7 (應該是 5...)word_count(' ') --> 輸出 = 2 (應該是 ''。我認為它正在執行 count(1+1))
查看完整描述

3 回答

?
嗶嗶one

TA貢獻1854條經驗 獲得超8個贊

使用此代碼作為改進


def word_count(str):

    count = 1

    for i in str:

        if (i == ' '):

           count += 1

    if str[0] == ' ':

        count -= 1

    if str[-1] == ' ':

        count -= 1

    print (count)

您的錯誤是因為您計算空格是否從開頭開始或出現在末尾。請注意,您不能傳遞空字符串,""因為它被計算為NONE,并且嘗試對其進行索引將導致錯誤


查看完整回答
反對 回復 2023-10-11
?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

問題似乎出在句子前面或后面有空格時。解決此問題的一種方法是使用內置函數“strip”。例如,我們可以執行以下操作:


example_string = " This is a string "

print(example_string)

stripped_string = example_string.strip()

print(stripped_string)

第一個字符串的輸出將是


" This is a string " 

第二個字符串的輸出將是


"This is a string"


查看完整回答
反對 回復 2023-10-11
?
BIG陽

TA貢獻1859條經驗 獲得超6個贊

您可以執行以下操作:


def word_count(input_str):

    return len(input_str.split())



count = word_count(' this is a test ')

print (count)

它基本上刪除了前導/尾隨空格并將短語拆分為列表。


如果您偶爾需要使用循環:


def word_count(input_str):

    count = 0

    input_str = input_str.strip()

    for i in input_str:

        if (i == ' '):

            count += 1                    

    return count


count = word_count(' this is a test ')

print (count)


查看完整回答
反對 回復 2023-10-11
  • 3 回答
  • 0 關注
  • 178 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號