2017-04-24 39 views
0

我有一個任務,寫一個代碼來計算字符串中的單詞。我還沒有學會分割,所以我不能使用它。我只能使用函數,循環和條件。他故意在字符串中添加了三個額外的空格,我必須弄清楚如何才能將它看作一個字符串。我卡住了。幫幫我!如何讓Python忽略多餘的空格?

def wordCount(myString): 
    try: 
     spaceCount = 0 
     char = "" 
     for i in myString: 
      char += i 
      if char == " ": 
       spaceCount == 1 
       pass 
      elif char == " ": 
       spaceCount += 1 
     return spaceCount+1 
    except: 
     return "Not a string" 

print("Word Count:", wordCount("Four words are here!")) 
print("Word Count:", wordCount("Hi David")) 
print("Word Count:", wordCount(5)) 
print("Word Count:", wordCount(5.1)) 
print("Word Count:", wordCount(True)) 
+0

馬上蝙蝠,讓我給你一些建議:儘量使你的'嘗試 - 除了'塊封裝了可能/有用的最小代碼量。並且*總是*顯式地捕獲一些錯誤類型,裸體'except'子句可以掩蓋你並不期待的錯誤! –

+0

你怎麼卡住了?什麼是或沒有發生? – wwii

+0

堆棧溢出不是讓人們來解決你的功課,但這裏有一個提示:做一個變量來跟蹤前一個字符。如果你得到一個空間,但最後一個角色也是一個空間,你不知道這個空間。 – dlsso

回答

1

這種作品:

def wordCount(myString): 
    try: 
     words = 0 
     word = '' 
     for l in myString : 
      if (l == ' ' and word != '') or (l == myString[-1] and l != ' ') : 
       words += 1 
       word = '' 
      elif l != ' ' : 
       word += l 
     return words 
    except Exception as ex : 
     return "Not a string" 

print("Word Count:", wordCount("Four words are here!")) 
print("Word Count:", wordCount("Hi David")) 
print("Word Count:", wordCount(5)) 
print("Word Count:", wordCount(5.1)) 
print("Word Count:", wordCount(True)) 

結果:

'Word Count:', 4 
'Word Count:', 2 
'Word Count:', 'Not a string' 
'Word Count:', 'Not a string' 
'Word Count:', 'Not a string' 
+0

你是一個救生員,那就是訣竅。謝謝! –

+0

很高興我可以幫助:) –

0
def wordCount(s): 
    try: 
     s=s.strip() 
     count = 1 
     for i,v in enumerate(s): 
      #scan your string in pair of 2 chars. If there's only one leading space, add word count by 1. 
      if (len(s[i:i+2]) - len(s[i:i+2].lstrip()) == 1): 
       count+=1 
     return count 
    except: 
     return "Not a string" 
print("Word Count:", wordCount("Four words are here! ")) 
print("Word Count:", wordCount("Hi David")) 
print("Word Count:", wordCount(5)) 
print("Word Count:", wordCount(5.1)) 
print("Word Count:", wordCount(True)) 
+0

我喜歡你的邏輯,但是如果開頭或結尾有空格呢? –

+0

我更新了應該處理您提到的情況的代碼。 – Allen

+0

還沒有,你錯過了開始 –